C Programming: Memory, Pointers and the Stack ยท Functions and Scope

Recursion and the Call Stack

sum_to(3) calls sum_to(2), then (1), then (0). Watch the frames pile up and unwind.

recursion.c

#include <stdio.h>

int sum_to(int n) {
    if (n == 0) {
        return 0;
    }
    return n + sum_to(n - 1);
}

int main(void) {
    int s = sum_to(3);
    printf("%d\n", s);
    return 0;
}

Step by step

  1. Start: sum_to(3).
  2. C checks n == 0 to decide which way the code goes.
  3. sum_to(3) needs sum_to(2), so it waits and a new frame is pushed.
  4. C checks n == 0 to decide which way the code goes.
  5. n changes from 2 to 1.
  6. C checks n == 0 to decide which way the code goes.
  7. n changes from 1 to 0.
  8. C checks n == 0 to decide which way the code goes.
  9. n == 0: the base case returns 0 without recursing.
  10. n changes from 0 to 1.
  11. n changes from 1 to 2.
  12. n changes from 2 to 3.
  13. sum_to() has finished, so its variables are gone. The value it returned, 6, is stored in s.
  14. It prints 6.
  15. The method returns 0.
  16. 6 = 3 + 2 + 1 + 0, built as the frames unwound.