Learn C++ · lesson 52 of 61 · about 8 minutes
Tracing and Fixing Recursion
Follow every call step by step, and spot recursion that never stops.
What you'll learn
- Trace the order of recursive calls
- Explain what the call stack is
- Fix a missing or unreachable base case
The echo cave
Past the treasure is a cave that echoes. The hero shouts a word, and the cave sends it back a letter shorter each time, then grows it again: ROAR, ROA, RO, R, RO, ROA, ROAR. That shape comes straight from the call stack. echo prints the shout on the way down, calls itself on the shout without its last letter, and prints the same shout again once that call has finished, on the way back up. Shouts of more than 8 letters are too long for the cave.
The call stack
Every call gets its own copy of its parameters and local variables, in a stack frame. When a function calls itself, the first call waits while the new one runs.
When the base case returns, the calls finish one by one, newest first. Code after the recursive call runs on the way back out.
In and out
#include <iostream>
void dive(int n) {
if (n == 0) {
std::cout << "bottom\n";
return;
}
std::cout << "going down " << n << "\n";
dive(n - 1);
std::cout << "coming up " << n << "\n";
}
int main() {
dive(2);
}Output
going down 2
going down 1
bottom
coming up 1
coming up 2When it never stops
If the base case is missing, or the calls never reach it, frames pile up until the stack runs out and the program crashes, usually with a segmentation fault or stack overflow. Check that every path makes the problem smaller and that the base case catches the smallest one.
Fibonacci: two calls each time
#include <iostream>
int fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
int main() {
for (int i = 0; i < 8; i++) std::cout << fib(i) << " ";
std::cout << "\n";
}Output
0 1 1 2 3 5 8 13Each call keeps its own shout
When echo("ROA") calls echo("RO"), its own shout is still ROA: the new call has a frame of its own. That's why the second print, after the call, prints the longer shout again rather than the shorter one.
A shorter word each call
#include <iostream>
#include <string>
void shrink(const std::string& word) {
std::cout << word << "\n";
if (word.size() > 1) {
shrink(word.substr(0, word.size() - 1));
}
}
int main() {
shrink("cave");
}Output
cave
cav
ca
cTip
fib calls itself twice, so the number of calls doubles quickly. fib(40) makes hundreds of millions of calls; a loop is far faster for that one.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.