Recursion in C++
Recursion solves a problem by having a function call itself on smaller inputs: a base case that answers directly, and a recursive step that shrinks toward it. Factorial, tree traversals, and divide-and-conquer algorithms read almost as their mathematical definitions when written this way.
Every call consumes stack space for its frame, so depth is bounded (millions of frames overflow) and the base case is load-bearing — miss it and the program recurses until it crashes. C++ compilers perform tail-call optimization in simple cases, but never rely on it; prefer iteration for deep linear problems.
Base case first
fact(0) = 1 answers without recursing — the anchor every call chain must be able to reach.
Shrink every step
fact(n) = n * fact(n-1) moves strictly toward the base case; a step that doesn't shrink loops forever.
Trust the contract
Assume the recursive call correctly solves the smaller instance — verify base case plus shrinkage, not the whole unfolding.
Mind the stack
Each live call holds a frame; recursion depth in the hundreds of thousands risks stack overflow — iterate deep linear recursions instead.
#include <iostream> int fact(int n) { if (n <= 1) return 1; return n * fact(n - 1);} int main() { std::cout << fact(5) << std::endl; return 0;}n calls each doing O(1) work, but n live stack frames at the deepest point.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.