Skip to content
Codescope

Recursion on the stack

Nothing special happens. A function calling itself gets a new frame, like any other call.

core9 min9 steps

Before you start

**Recursion** is a function calling itself. That sounds like it should either be impossible or an infinite loop, but neither is true — each call gets its own frame with its own copy of the variables, so the calls don't interfere.

Recursion is powerful because some problems are naturally self-similar. "Calculate 5!" is really "take 5, multiply it by 4!, and 4! is 4 times 3!, and…" — each step is a smaller version of the same question.

This lesson watches recursive calls stack up frame by frame, hit the *base case* that stops them, and then unwind back to the answer.

Stack

one frame per live call
main()
no locals yet

waiting on fact(4) — line 10

fact(4)depth 1
nint
4
0x7ffd7fe0

Step 1 of 9. main calls fact(4). One frame for `main`, one for `fact(4)`. So far this is an ordinary function call. `n` is 4, which is greater than 1, so the base case is skipped and line 6 runs.

01 / 09

Step 01 / 09

main calls fact(4)

One frame for main, one for fact(4). So far this is an ordinary function call.

n is 4, which is greater than 1, so the base case is skipped and line 6 runs.

recursion-and-the-stack.cC
#include <stdio.h>int fact(int n) {    if (n <= 1)        return 1;    return n * fact(n - 1);}int main(void) {    printf("%d\n", fact(4));    return 0;}