Sub topic 17
Tracing recursive calls and predicting output
This chapter assumes you know how the call stack works, so you can picture a stack frame holding a function's parameters, local variables and return address. It also assumes you know what a base case and a recursive case are. Here you will turn that knowledge into a repeatable procedure for predicting what a recursive C function prints or returns.
The working model
Every call creates a new frame with its own copy of each parameter and local variable. A frame is destroyed when its function returns. Because of this, the n in one call is a different variable from the n in the call it makes.
A recursive function runs in two phases:
- Winding. Statements before the recursive call run on the way down, so the first call's "before" code runs first.
- Unwinding. Statements after the recursive call run on the way back up, in the reverse order of the calls.
Most output-prediction questions come down to knowing which side of the recursive call a statement sits on.
#include <stdio.h>
void show(int n) {
if (n == 0) {
return;
}
printf("in %d\n", n);
show(n - 1);
printf("out %d\n", n);
}
int main(void) {
show(3);
return 0;
}The output is in 3, in 2, in 1, out 1, out 2, out 3, each on its own line. The "in" lines count down because they run while winding. The "out" lines count up because the frames finish in last-in, first-out order. Moving the first printf below the recursive call would print only the "out" order.
A tracing procedure
- Write down the first call with its argument values.
- Check the base case. If it applies, record the return value or output and stop.
- Otherwise, write the next call and keep descending. Note which statements are still waiting in each open frame.
- When a call returns, substitute its value into the waiting expression of the frame below it.
- Continue until the first call returns.
For a function that returns a value, keep a table with one row per call.
int g(int n) {
if (n == 0) {
return 0;
}
return g(n / 2) * 10 + n % 2;
}Tracing g(6):
| Call | n | Waiting expression | Returns |
|---|---|---|---|
| g(6) | 6 | g(3) * 10 + 0 | 110 |
| g(3) | 3 | g(1) * 10 + 1 | 11 |
| g(1) | 1 | g(0) * 10 + 1 | 1 |
| g(0) | 0 | base case | 0 |
Fill the table from the top down, then resolve the Returns column from the bottom up. The result is 110, the binary digits of 6 read as a decimal number.
Tracing tree recursion
When a function makes two recursive calls, the calls form a tree. The printing order follows a depth-first walk of that tree. The left call finishes completely before the right call starts.
#include <stdio.h>
int fib(int n) {
printf("enter %d\n", n);
if (n < 2) {
return n;
}
int a = fib(n - 1);
int b = fib(n - 2);
return a + b;
}
int main(void) {
printf("result %d\n", fib(3));
return 0;
}The output is enter 3, enter 2, enter 1, enter 0, enter 1, result 2. Each line is one call, listed in the order the calls begin. The first enter 1 comes from fib(2) calling fib(1). The enter 0 comes from fib(2) calling fib(0). The last enter 1 comes from fib(3) calling fib(1).
The tree has nine nodes, so fib(4) makes nine calls. If C(n) is the number of calls, then C(n) = 1 + C(n-1) + C(n-2) with C(0) = C(1) = 1. This gives 1, 1, 3, 5, 9, 15, and so on. The tree also shows repeated work: fib(2) is computed twice and fib(1) three times. The next chapters turn this into a complexity argument.
The stack depth is different from the number of calls. At any moment only the frames along one root-to-node path exist. For fib(n) that is at most n frames, even though the total number of calls grows exponentially.
Shared state versus frame state
Local variables belong to a frame. Global variables and static locals are shared by every call, and this changes the trace.
#include <stdio.h>
int count(int n) {
static int s = 0;
if (n == 0) {
return s;
}
s += n;
return count(n - 1);
}
int main(void) {
printf("%d\n", count(3));
return 0;
}There is exactly one s. It is initialized once, before the first call runs. The calls add 3, then 2, then 1, so the program prints 6. If s were an ordinary local, each frame would start from an uninitialized value and the function would be wrong.
Pointer arguments also share state. If a recursive function receives int *total, every frame updates the same object. Trace such functions by keeping a separate cell for the shared variable and updating it as the calls happen, not by copying it into each frame.
Common errors
- Reading the unwinding as if it were winding. Mark each statement as before or after the recursive call before tracing.
- Treating arguments as shared. Changing n in one frame does not affect the caller's n.
- Using
n++or--nin a recursive call. The call f(n++) passes the old value of n. The new frame receives the same value again, so the recursion never reaches its base case. The program overflows the stack, which is undefined behavior. - Forgetting the base case or never moving toward it. Frames pile up until the stack is exhausted.
- Losing track of pending work. An expression like
n * f(n - 1)still has a multiplication waiting after the call returns. This is also why the function is not tail recursive.
Exercises
#include <stdio.h>
void p(int n) {
if (n > 0) {
p(n - 1);
printf("%d ", n);
p(n - 1);
}
}Exercise
What does the call p(3) print, using the function above?
Show answer
It prints "1 2 1 3 1 2 1". p(3) calls p(2), which prints "1 2 1" (p(1) prints 1, then 2 is printed, then p(1) prints 1 again). Then p(3) prints 3, and finally calls p(2) again, which prints "1 2 1" a second time.
Exercise
Using C(n) = 1 + C(n-1) + C(n-2) with C(0) = C(1) = 1, how many calls does fib(6) make, and what does it return?
Show answer
C(2) = 3, C(3) = 5, C(4) = 9, C(5) = 15, so C(6) = 1 + 15 + 9 = 25 calls. The return value is fib(6) = 8.
Exercise
A recursive function has no reachable base case. What happens when it runs?
Show answer
Each call adds a new frame to the call stack, and none is ever removed. The stack eventually runs out of space. The behavior is undefined by the C standard, and in practice the program usually crashes with a stack overflow or segmentation fault.