When fact(3) called fact(2), it didn't disappear — it paused, half-finished,
waiting for an answer. This lesson is about where those paused calls wait, and
what you can do with the moment each one wakes up again.
Every call gets its own frame
Calling a function creates a frame: a small block of memory holding that call's parameters and local variables, and the place to come back to when it finishes. Frames pile up on the call stack — the newest on top — and only the top one is running. When it returns, its frame is thrown away and the one below carries on from exactly where it paused.
Two things follow:
- Each call has its own copy of its variables. The
ninsidefact(2)and theninsidefact(3)are different boxes — changing one never touches the other. - The calls finish in reverse order: the last one called is the first to return.
Work on the way down, work on the way back
A recursive call splits a function into two halves: the code before the call runs while the calls are going deeper, and the code after it runs while they return — in reverse order. Step through a function that prints in both places: