security consultant, hacker, surfer
(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 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.
Create your free account to unlock your custom reading experience.