What Happens When You Call a Function?
(Visual of the call stack executing. Start at frame #0.)
My above visual of the call stack executing may appear overwhelming / chaotic. I would strongly recommend tracing it out yourself. Python Tutor (can handle many other languages) is also a great resource for visualizing how the stack changes.
Let’s briefly run through what’s happening under the hood when we make recursive calls to p_sum() starting in main() at frame #0:
- The parameters for p_sum() are pushed on to the stack in the reverse order they are listed in the argument list.
- The return address of the main() function is pushed onto the stack so p_sum() will know where to return control to once it’s finished executing. Control is now transferred to p_sum().
- Any local variables defined in p_sum() are pushed onto the stack frame.
The same process is repeated (with updated values) until the base case is reached and frames begin popping off the stack:
3. Local variables are popped off the stack frame.
2. Control is returned to the previous stack frames and the return address is popped off the stack frame.
1. The parameters used to call the function that has just terminated are popped of the stack frame.
0. The stack frame is now empty and is popped off the stack.
Hopefully you are more aware of what’s actually happening on the call stack when functions are called. This should give you a stronger handle on recursion and make debugging recursive programs easier.
Subscribe to get your daily round-up of top tech stories!