---
title: Recursion and stack frames
heading: Functions that call themselves, one frame at a time
eyebrow: C8 · Lesson 15 · Recursion and stack frames
xp: 40
---

::: hook
Lesson 14's calling convention is exactly what makes recursion work. Every call gets its own **stack frame**, a slice of the stack holding its saved return address and whatever values it needs after the next call returns, so each level of a recursive function keeps its own copy of its argument while deeper levels run. Watch the stack pointer as a recursive function runs and you'll see it step down one frame per level, then climb back as the answers combine on the way out.
:::

::: play
- A recursive Fibonacci: `fib(n)` returns n when n < 2, otherwise fib(n − 1) + fib(n − 2). It's called with n = 6, and t6 counts the calls.
- Step it and watch sp. Each call that recurses makes a 16-byte frame holding ra, n and, once the first call returns, fib(n − 1). The stack is never more than five frames deep.
- Run it to the end: a0 = 8 and t6 = 25, so fib(6) took 25 calls although it's only five levels deep. The same small values are worked out again and again.
:::
:::

```sim cpu
.text
    li a0, 6
    li t6, 0            # counts calls (nothing else here touches t6)
    call fib
    ebreak
fib:
    addi t6, t6, 1
    li t0, 2
    blt a0, t0, done    # fib(0) = 0 and fib(1) = 1: a0 is already the answer
    addi sp, sp, -16    # make a frame
    sw ra, 12(sp)       # save the return address
    sw a0, 8(sp)        # and n
    addi a0, a0, -1
    call fib            # a0 = fib(n - 1)
    sw a0, 4(sp)        # keep it in the frame
    lw a0, 8(sp)
    addi a0, a0, -2
    call fib            # a0 = fib(n - 2)
    lw t1, 4(sp)
    add a0, a0, t1      # fib(n - 1) + fib(n - 2)
    lw ra, 12(sp)
    addi sp, sp, 16     # free the frame
done:
    ret
show: a0, t6, t1
hex: sp, ra
memory: 0xFFB0..0x10000
speed: 25
```

::: predict
## A recursive function uses a 16-byte frame per call. Called with n = 1000, it recurses 999 levels deep. How much stack does it need?

- [ ] 16 bytes
- [ ] 1000 bytes
- [x] About 16 kB
- [ ] 16 MB

::: reveal
About 16 kB: 999 frames of 16 bytes are all live at once at the deepest point. On a small microcontroller with a few kilobytes of RAM that overflows the stack, which is why embedded code avoids deep recursion.
:::
:::

::: nameit
## The stack frame

A non-leaf function (one that calls others) must save **ra**, since its own call will overwrite it, and any values it needs after the call that live in caller-saved registers (the a and t registers). It also saves any s registers it uses. The usual shape:

```asm
f:  addi sp, sp, -16      # allocate the frame
    sw   ra, 12(sp)
    sw   s0, 8(sp)        # save what you'll use
    ...                   # body, including calls
    lw   s0, 8(sp)
    lw   ra, 12(sp)
    addi sp, sp, 16       # free it
    ret
```

The RISC-V convention keeps sp a multiple of 16. A **leaf** function, which calls nothing, can often skip the frame entirely.

## Recursion

Each level's frame holds that level's values, so recursion needs no special support. Its cost is stack: the **depth** times the frame size, all at once at the deepest point. A **tail call** (calling as the very last action) can reuse the current frame, so tail recursion compiles to a loop.

## Counting calls

Some recursions branch: the naive Fibonacci, $F(n) = F(n - 1) + F(n - 2)$, makes $2F(n + 1) - 1$ calls to compute $F(n)$, exponential in n, although its depth is only n. The same results computed in a loop take n steps.
:::

::: example
## How deep does `fib(6)` go, and how much stack does it use with 16-byte frames?

::: solution
1. **Find the deepest chain.** fib(6) → fib(5) → fib(4) → fib(3) → fib(2) → fib(1).
2. **Count the frames.** The first five make frames before calling, and fib(1) returns at once, so there are 5 frames, 80 bytes, at the deepest point.
3. **Where sp goes.** It goes down from 0x10000 to 0xFFB0.
4. **The other branches.** They are shallower and reuse the same stack space.

**Answer:** five frames deep, 80 bytes of stack, with sp going down to 0xFFB0.
:::
:::

::: example
## How many calls does the naive recursive Fibonacci make to compute F(10)?

::: solution
1. **Count the calls.** With F(11) = 89:
   $$\begin{aligned} \text{calls} &= 2 \times 89 - 1 \\ &= 177 \end{aligned}$$
   to get F(10) = 55.
2. **A loop instead.** A loop that starts from F(0) and F(1) needs 9 additions.

**Answer:** 177 calls, against 9 additions for a loop.
:::
:::

::: example
## A recursive factorial uses a 16-byte frame per call. How much stack does `fact(10)` need, and what does a loop need?

::: solution
1. **Count the live frames.** fact(10) calls fact(9) and so on down to fact(1), which returns without recursing: 10 frames are live at the deepest point.
2. **The stack they use.**
   $$10 \times 16 = 160\ \text{bytes}$$
3. **A loop.** A loop multiplying a running product needs no frames at all.
4. **Tail calls.** Many compilers turn a recursive call in tail position (the last thing a function does) into a jump, but factorial's multiplication after the call keeps it out of tail position unless it's rewritten with an accumulator.

**Answer:** `fact(10)` needs 160 bytes of stack, and a loop needs none.
:::
:::

::: check
given: n = 10 | 100 | 1000; f = 16 | 32 | 48
answer: (n - 1)*f
unit: bytes
tolerance: 0

## A recursive function with a {f}-byte frame is called with n = {n}; levels n down to 2 each make a frame before recursing, and level 1 returns at once. How much stack is in use at the deepest point?

::: right
Right. (n − 1) frames: {answer}.
:::

::: misses
- [n*f] Level 1 returns without making a frame.
- [any] Not yet. Count the frames live at once.
:::
:::

::: check
given: n = 5 | 8 | 12 | 15; let F = (((1 + sqrt(5))/2)^(n + 1) - ((1 - sqrt(5))/2)^(n + 1))/sqrt(5)
answer: 2*F - 1
tolerance: 0.1%

## How many calls does the naive recursive Fibonacci make to compute F({n})?

::: right
Right. $2F(n + 1) - 1$ = {answer}.
:::

::: misses
- [n] That's the depth; the calls branch two ways.
- [any] Not yet. $2F(n + 1) - 1$.
:::
:::

::: check
kind: asm
given: n = 6..15 int
setup: a0 = n
expect: a0 = round(((1 + sqrt(5))/2)^n/sqrt(5))

## With n in a0, leave the Fibonacci number F(n) in a0, where F(0) = 0, F(1) = 1 and each later one is the sum of the two before. (A recursive version or a loop: either is fine.)

```asm starter
    # n is in a0
    ebreak
```

```asm solution
    call fib
    ebreak
fib:
    li t0, 2
    blt a0, t0, done
    addi sp, sp, -16
    sw ra, 12(sp)
    sw a0, 8(sp)
    addi a0, a0, -1
    call fib
    sw a0, 4(sp)
    lw a0, 8(sp)
    addi a0, a0, -2
    call fib
    lw t1, 4(sp)
    add a0, a0, t1
    lw ra, 12(sp)
    addi sp, sp, 16
done:
    ret
```

::: right
Right. If you wrote it recursively, each level kept its own n and its first result in its frame; if you wrote a loop, it ran in a fraction of the instructions.
:::
:::

::: check
kind: choice

## Inside a recursive function, n arrives in a0 and is needed after the recursive call. Where should it be kept across the call?

- [ ] In a0: the call won't change it
- [ ] In t0
- [x] In the function's stack frame (or an s register the function saves)
- [ ] In ra

::: misses
- [1] a0 carries the argument and the result of the call; it will change.
- [2] t registers are caller-saved: the call may overwrite them.
- [4] ra holds the return address, which the call overwrites.
:::
:::

::: check
kind: choice

## Which functions must save ra on the stack?

- [ ] All functions
- [x] Functions that call other functions
- [ ] Only recursive functions
- [ ] Functions that use s registers

::: misses
- [1] A leaf function never overwrites ra.
- [3] Any call overwrites ra, recursive or not.
- [4] Saving s registers is a separate rule; ra is about calls.
:::
:::

::: check
kind: parts
given: n = 5 | 10 | 20 | 30; f = 16 | 32

## A naive recursive Fibonacci computes F({n}) with {f}-byte frames.

::: part
answer: (n - 1)*f
tolerance: 0

### How much stack does it use at the deepest point?

::: misses
- [n*f] The deepest chain ends at F(1), which returns without a frame.
- [any] One frame per level, n − 1 levels.
:::
:::

::: part
answer: n - 1
tolerance: 0

### How many additions does a loop need instead?

::: misses
- [any] One per step from F(1) up.
:::
:::
:::

::: check
kind: asm
given: n = 2..12 int
setup: a0 = n
expect: a1 = n!

## With n in a0 (at most 12), put n! into a1.

```asm starter
    li a1, 1
    ebreak
```

```asm solution
    li a1, 1
loop:
    beqz a0, done
    mul a1, a1, a0
    addi a0, a0, -1
    j loop
done:
    ebreak
```

::: right
Right. The loop version needs no stack at all.
:::
:::

::: explain
## Why does each level of a recursive function keep its own value of n, even though every level uses the same code?

::: model
The code is shared, but the data isn't: every call allocates a new stack frame by moving the stack pointer down, and saves its own n there before calling itself. The deeper call makes a frame further down and saves its own, different n. When a call returns it frees only its own frame, so the stack pointer is back exactly where the caller left it, pointing at the caller's frame, and the caller reloads its own n from there. The stack holds one frame per active call, so as many copies of n as there are levels.
:::
:::

::: practice

::: check
given: d = 3 | 20 | 100; f = 16 | 64
answer: d*f
unit: bytes
tolerance: 0

## How much stack do {d} live frames of {f} bytes take?

::: misses
- [any] Depth times frame size.
:::
:::

::: check
given: x = 20 | 40 | 72
answer: 16*ceil(x/16)
unit: bytes
tolerance: 0

## A function needs {x} bytes of locals and saved registers. How large is its frame, keeping sp a multiple of 16?

::: misses
- [any] Round up to a multiple of 16.
:::
:::

::: check
given: n = 3 | 6 | 10; f = 16 | 32
answer: (n - 1)*f
unit: bytes
tolerance: 0

## A function recursing {n} levels deep with {f}-byte frames is rewritten as a loop that uses a single frame. How many bytes of stack does that save at the deepest point?

::: misses
- [any] n frames become one.
:::
:::
:::
