C Programming: Memory, Pointers and the Stack ยท Functions and Scope
sum_to(3) calls sum_to(2), then (1), then (0). Watch the frames pile up and unwind.
#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;
}n == 0 to decide which way the code goes.n == 0 to decide which way the code goes.n changes from 2 to 1.n == 0 to decide which way the code goes.n changes from 1 to 0.n == 0 to decide which way the code goes.n changes from 0 to 1.n changes from 1 to 2.n changes from 2 to 3.sum_to() has finished, so its variables are gone. The value it returned, 6, is stored in s.6.0.