The call stack
After this: Follow frames as they are added and removed, and say what has been worked out at each moment.
On this page · 6 sections · 3 checks
In the last lesson, factorial(3) called factorial(2), and each call had its own n. But factorial(3) still needs its 3 after the smaller call comes back. Where does the computer keep that 3 while the smaller call runs?
Think of the line of people again. While Ben waited for Ana's answer, he had to remember one thing: "When the answer comes, I add one." The computer needs the same kind of reminder for every call. This lesson shows where it keeps them.
A frame is a note about one call
When a function is called, the computer creates a small record for that call. This record is called a . A frame holds three things:
- which function is running
- the values of its arguments and local variables
- the place in the code to carry on from when a call it made comes back
The frames are kept in a stack. A stack is a pile where you add and remove items only at the top, as you saw in the stacks and queues tutorial. Adding an item is called a push, and removing one is called a pop. This stack is called the .
The rules are short.
- When a function is called, its frame is pushed on top.
- Only the top frame runs. The frames below it wait.
- When a function returns, its frame is popped. The return value goes to the frame below, which carries on from where it stopped.
This happens for every function call, recursive or not. Recursion makes the stack taller, because each call starts another call before it finishes.
The stack, step by step
Here is the smallest useful example, factorial(2). The right-hand column shows the call stack after each step, with the top frame first.
| Step | What happens | Stack, top first |
|---|---|---|
| 1 | Call factorial(2). Push its frame. | factorial(2) |
| 2 | It needs factorial(1), so it calls it and waits. | factorial(1), factorial(2) |
| 3 | factorial(1) needs factorial(0), so it calls it and waits. | factorial(0), factorial(1), factorial(2) |
| 4 | factorial(0) is the base case. It returns 1 and is popped. | factorial(1), factorial(2) |
| 5 | factorial(1) works out 1 × 1, returns 1 and is popped. | factorial(2) |
| 6 | factorial(2) works out 2 × 1, returns 2 and is popped. | empty |
In step 3 there are three variables called n, with the values 0, 1 and 2. They do not clash, because each one lives in its own frame.
factorial(3) works the same way with one more frame. It pushes four frames before anything is multiplied: 3, 2, 1, 0. The top one, factorial(0), returns 1 at once. Then the frames pop one at a time, and each one does its multiplication as it finishes. The values that come back are 1, 1, 2 and 6.
You can see this by making factorial print a line for each call and each return.
def factorial(n, depth=0): print(" " * depth + f"call factorial({n})") if n == 0: result = 1 else: result = n * factorial(n - 1, depth + 1) print(" " * depth + f"factorial({n}) returns {result}") return result
factorial(3)call factorial(3)
call factorial(2)
call factorial(1)
call factorial(0)
factorial(0) returns 1
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6static int factorial(int n, int depth) { System.out.println(" ".repeat(depth) + "call factorial(" + n + ")"); int result; if (n == 0) result = 1; else result = n * factorial(n - 1, depth + 1); System.out.println(" ".repeat(depth) + "factorial(" + n + ") returns " + result); return result;}
factorial(3, 0);call factorial(3)
call factorial(2)
call factorial(1)
call factorial(0)
factorial(0) returns 1
factorial(1) returns 1
factorial(2) returns 2
factorial(3) returns 6Here is how to read it.
- The new argument
depthcounts how many calls deep we are. Each smaller call getsdepth + 1. - The function uses
depthto indent its lines, so the indentation shows how tall the stack is. - Every "call" line is a push, and every "returns" line is the moment before a pop.
Look at the output. The returns come out in the opposite order to the calls. The last call to start is the first to finish, which is the "last in, first out" rule of a stack.
Watch it happen
- factorial(3)Go through this one step at a time. Pause when factorial(0) is pushed: there are four frames, three of them are waiting, and nothing has been multiplied yet.
- countdown(3)
- empty
- no calls yet
Call a function to push its first frame.
- calls
- 0
- depth
- 0
Step through factorial(3) one step at a time. When factorial(0) is pushed, four frames are on the stack, and three of them are waiting. Each waiting frame remembers its n and has one multiplication left to do. At that moment nothing has been multiplied yet, so the answer to factorial(3) is not stored anywhere. It exists only when the last frame finishes.
Before the call, or after
A recursive function can do its work before its smaller call or after it. This choice decides when the work happens.
countdown from the last lesson prints before it makes its smaller call. So the prints come out while the calls are going down: 3, 2, 1, then liftoff.
def countdown(n): if n == 0: # base case: stop here print("liftoff") return print(n) # recursive case: one small piece of work... countdown(n - 1) # ...then the same job with a smaller number
countdown(3)3 2 1 liftoff
static void countdown(int n) { if (n == 0) { // base case: stop here System.out.println("liftoff"); return; } System.out.println(n); // recursive case: one small piece of work... countdown(n - 1); // ...then the same job with a smaller number}
countdown(3);3 2 1 liftoff
Now imagine moving the print after the call. Each frame would make its smaller call first, and its print would wait in the frame until that call has returned. So the prints would come out while the frames are popping, on the way back up. The last check in this lesson asks you to work out what that prints.
Check yourself
During factorial(3), what is the largest number of frames on the call stack at one moment?
As the four frames of factorial(3) pop, which values come back, in order?
countdown printed before its smaller call. This function prints after its smaller call. What does it print?
def count_up(n): if n == 0: print("start") return count_up(n - 1) # wait for the smaller call first... print(n) # ...then do the work, after it returns
count_up(3)static void countUp(int n) { if (n == 0) { System.out.println("start"); return; } countUp(n - 1); // wait for the smaller call first... System.out.println(n); // ...then do the work, after it returns}
countUp(3);Connect
- Describe a frame as the record of one call, and the call stack as the pile of frames for all unfinished calls.
- Describe a call as pushing a frame, and a return as popping it and handing the value to the frame below.
- Follow factorial(3): four frames pushed (3, 2, 1, 0), and the values coming back as 1, 1, 2, 6.
- Tell whether work happens on the way down or on the way back, from whether it sits before or after the call.