paint-brush
What Happens When You Call a Function?by@silver.io
442 reads
442 reads

What Happens When You Call a Function?

by silver.ioApril 13th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Python Tutor (can handle many other languages) is also a great resource for visualizing how the call stack changes. The parameters for p_sum() are pushed on to the stack in the reverse order they are listed in the argument list. The same process is repeated (with updated values) until the base case is reached and frames begin popping off the stack. This should give you a stronger handle on recursion and make it easier to understand recursion. The call stack is now empty and the stack frame is empty.
featured image - What Happens When You Call a Function?
silver.io HackerNoon profile picture


(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.