Functions and the Call Stack

Every function call gets its own frame: a private scratch-pad, stacked on top of the caller’s.

The idea

Picture a stack of sticky notes on your desk. You are working on a task (main). You need a sub-task done, so you put a fresh note on top with the inputs written on it and work only on that note. When it is finished you read off the answer, throw the note away, and carry on with the one underneath.

Arguments are copied onto the new note, so the callee can scribble on its notes without touching yours. A function that calls itself (recursion) just keeps adding notes until it reaches a case it can answer immediately, then the answers flow back down the stack.

Watch it work

Try it

Common mistakes