0

This is not a homework question. I'm merely trying to understand the process for my own edification. As a computer science student, I have attended several lectures where the concept of recursion was discussed. However, the lecturer was slightly vague, in my opinion, regarding the concept of a stack frame and how the call stack is traversed in order to calculate the final value. The manner in which I currently envision the process is analogous to building a tree from the top down (pushing items onto the call stack - a last in, first out data structure) then climbing the newly constructed tree where upon the final value is obtained upon reaching the top. Perhaps the canonical example:

def fact(n):
    if n == 0: 
        ans = 1
    else:
        ans = n * fact(n-1)
    return ans

value = fact(5)
print (value)

As indicated above, I think the call stack eventually resembles the following (crudely) drawn diagram:

+----------+
|    5      |
|    4      | 
|    3      |
|    2      |
|    1      |
 +----------+

Each number would be "enclosed" within a stack frame and control now proceeds from the bottom (with the value of 1) to the 2 then 3, etc. I'm not entirely certain where the operator resides in the process though. Would I be mistaken in assuming an abstract syntax tree (AST) in involved at some point or is a second stack present that contains the operator(s)?

Thanks for the help.

~Caitlin

Edit: Removed the 'recursion' tag and added 'function' and 'stackframe' tags.

CaitlinG
  • 1,955
  • 3
  • 25
  • 35

2 Answers2

1

The call stack frame stores arguments, return address and local variables. The code (not only the operator) itself is stored elsewhere. The same code is executed on different stack frames.

You can find some more information and visualization here: http://www.programmerinterview.com/index.php/recursion/explanation-of-recursion/

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
1

This question is more about how function calls work, rather than about recursion. When a function is called a frame is created and pushed on the stack. The frame includes a pointer to the calling code, so that the program knows where to return after the function call. The operator resides in the executable code, after the call point.

Joni
  • 108,737
  • 14
  • 143
  • 193