Common Recursion Pitfalls
You'll learn to recognize and avoid the three most common mistakes that break recursive functions: missing base cases, incorrect recursive calls, and excessive recursion depth.
The Core Idea
Even when you understand how recursion works, it's easy to make mistakes that cause your program to crash or behave unexpectedly. These errors are so common they have names, and learning to spot them will save you hours of debugging.
Missing Base Cases
The base case is your exit condition. Without it, your recursion never stops—like giving directions that say "turn left" forever without saying when to stop. Your program will keep calling itself until it runs out of memory (stack overflow).
Example pitfall: Forgetting to check if n == 0 when computing a factorial, so it keeps calling itself with negative numbers indefinitely.
Incorrect Recursive Calls
Your recursive call must make progress toward the base case. If it doesn't change the problem or changes it in the wrong direction, you'll recurse forever or produce wrong results.
Example pitfall: Writing a countdown function that calls countdown(n) instead of countdown(n - 1)—the problem never gets smaller, so you never reach the base case.
Excessive Recursion Depth
Even correct recursion can fail if the problem is too large. Computing fibonacci(50) might make millions of recursive calls, quickly exhausting your call stack or taking forever to complete. Some problems need iteration or a different approach (like helper functions with extra parameters).
Example pitfall: Using naive recursive Fibonacci on large numbers—it works for small inputs but explodes for larger ones.
Prevention Checklist
- Always identify your base case(s) first
- Verify each recursive call moves toward the base case
- Test with small inputs before scaling up
- Consider iteration for very deep recursion
Key Takeaway: The three recursion killers are missing base cases (no exit), incorrect recursive calls (no progress), and excessive depth (too many calls)—always check for these when writing or debugging recursive functions.