Intermediate 8 min

The call stack

The call stack remembers which function should continue after the current function returns.

How it works

When main calls A, it pauses and leaves a place for execution to resume. A does this again when it calls B. B finishes first, then the paused A resumes. This last-in, first-out order also explains why too many nested calls can fill the stack.

Walk through an example

If main calls total and total calls price, price returns first, then total, then main. Each call has its own local context.

What to watch for

Too many nested calls can exhaust the stack. A recursive function needs a reachable base case and a reliable move toward it.

Check your understanding

Which function resumes immediately after B returns?

See the example and explanation
Worked example
Given main calls A, and A calls B.
Answer A.

A is the most recent unfinished caller, so execution resumes where A called B.

Open practice problem
Next lessonFloating-point precision