The call stack in recursion
What you'll learn: How the computer remembers where it is during recursive calls using a structure called the "call stack."
The mental bookmark
Imagine you are reading a book and you encounter a word you don't know. You stick your finger in the page to save your place, pick up a dictionary, and start reading a definition. Inside that definition, there is another word you don't know. You put a bookmark in the dictionary and pick up a second, specialized encyclopedia.
Once you finish the encyclopedia entry, you return to the dictionary where you left off. Once the definition is clear, you return to your original book. Each "bookmark" is a layer on a stack. In C, this is exactly how recursion works: the computer uses the Call Stack to remember where each function left off.
Stack frames in action
Every time a function calls itself, C creates a "stack frame." This frame stores the current value of local variables and the "return address" (the line of code to go back to). These frames are piled on top of each other. The function at the very top is the only one currently active.
Consider this simple countdown:
#include <stdio.h>
void count(int n) {
if (n <= 0) return; // Base case
printf("Pushing %d\n", n);
count(n - 1); // Recursive call
printf("Popping %d\n", n);
}
int main() {
count(3);
return 0;
}
The "Wind" and "Unwind"
When count(3) is called, a frame for n=3 is pushed onto the stack. It hasn't finished yet; it's waiting for count(2) to finish. Then count(2) waits for count(1). This is the winding phase.
Once the base case (n <= 0) is reached, no new frames are added. Now, the stack begins to unwind. The computer looks at the top frame, finishes the code after the recursive call (the "Popping" print statement), and deletes that frame. It then drops back down to the previous frame and continues where it left off.
If you recurse too many times without hitting a base case, you run out of memory. This is the famous Stack Overflow—the pile of bookmarks has become too tall for the room to hold.
Key takeaway
Recursion works because the call stack "pauses" unfinished functions and stacks them up, then completes them in reverse order once the base case is hit.