sum_to(3) calls sum_to(2), then (1), then (0). Watch the frames pile up and unwind.
C · beginner · 7 min · 16 steps · free
#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.Answer: 10. 4 + 3 + 2 + 1.
Answer: A stack overflow. Frames never stop.
← Pass by Value vs Pass a Pointer · Scope: Local, Global and static →