Problem Solving Fundamentals · Recursion

What the call stack does

the call stack

What the call stack does

Make a call inside a call inside a call and something has to remember where each one was, because the last one to start is the first one to finish. Picture a stack of plates: you set each new plate on top, and you take them off from the top too. A plate cannot slide out of the middle.

Every time a function calls another, the runtime puts a frame on that stack — the plate. The frame remembers where the call came from and what still has to happen once it returns. factorial(5) pushes a frame, then calls factorial(4), which pushes the next, down to the base case. Nothing has been multiplied yet; the frames sit waiting.

At the base case the stack turns around. factorial(1) returns its 1, and its frame comes off the top, handing the result back to factorial(2). Each frame finishes in the reverse of the order it was stacked, until the first call returns the final answer. Stack up on the way down, unwind on the way up.

The stack has a limit. If a function keeps calling itself with no base case, the frames pile up until there is no room, and the runtime throws a stack overflow — the error that means the plates never stopped.

You are about to answer a quiz on the call stack.

  1. Each function call adds a frame to the call stack.
  2. A stack is last in, first ___ — the most recent call finishes first.
  3. When a recursive call returns, its frame is removed and the caller continues.
  4. A recursive function with no base case piles up frames until it throws a stack ___.
  5. The multiplications in a recursive factorial happen on the way down, before the base case returns.
  6. The frames stack up on the way down and ___ on the way up.