문제

Function calls are handled via a stack data structure. Is this enough for supporting recursion?

도움이 되었습니까?

해결책

Having the stack at all is the special treatment the compiler has to have when supporting recursion.

In older programming languages like early versions of FORTRAN, the runtime environment did not have a function stack and each function had exactly one activation record reserved for it somewhere in memory. That meant that recursion wasn't at all possible, because if you recursively called a function you would overwrite its one and only activation record, losing track of the context of how you arrived there.

The introduction of the function stack is what first enabled recursion to be actually expressed in a programming language. Prior to that, programmers would use recursion as a tool for abstractly solving a problem, but would then have to translate that code into iterative logic due to the lack of a call stack.

In order for a programming language to support recursion, it needs to have some mechanism for dynamically maintaining the call stack. This doesn't have to be through an explicit stack; you could in theory dynamically-allocate all of the stack frames and chain them together as a linked list. This can be useful, for example, if you want to support coroutines or closures and actually need to hold on to old activation records after the function returns so that the data can be stored later.

Hope this helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top