Before you go, check out these stories!

Hackernoon logoWhat Happens When You Call a Function?

What Happens When You Call a Function?

Author profile picture

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:

  1. The parameters for p_sum() are pushed on to the stack in the reverse order they are listed in the argument list.
  2. 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().
  3. 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.


Join Hacker Noon

Create your free account to unlock your custom reading experience.