Course contentsShow
← Computer Science
Lesson 219 of 2,8725. Functions and ModularityFree lesson

Anatomy of a Recursive Call

Trace how a recursive function call creates a new stack frame with its own local variables and parameters.

Anatomy of a Recursive Call

You'll learn: How each recursive function call creates its own isolated stack frame with separate local variables and parameters.

The Core Idea

When a function calls itself recursively, the computer doesn't just "reuse" the same memory space. Instead, it creates a brand new stack frame—think of it as a fresh workspace—for each call. This frame holds its own copy of all parameters and local variables, completely separate from other active calls.

Imagine a stack of cafeteria trays: each recursive call adds a new tray on top. Each tray has its own labeled compartments for parameters and local variables. When a call finishes (hits its base case or returns), its tray is removed from the stack.

How It Works

Let's trace factorial(3):

factorial(3) creates Frame #1: n=3
  → calls factorial(2), creates Frame #2: n=2
    → calls factorial(1), creates Frame #3: n=1
      → calls factorial(0), creates Frame #4: n=0
        → base case! returns 1
      → Frame #4 removed, Frame #3 computes 1*1, returns 1
    → Frame #3 removed, Frame #2 computes 2*1, returns 2
  → Frame #2 removed, Frame #1 computes 3*2, returns 6
→ Frame #1 removed, final answer: 6

Each frame's n is independent. Frame #1's n=3 doesn't change when Frame #2 works with n=2. They coexist on the stack simultaneously until they finish and get removed in reverse order (last created, first removed).

Why This Matters

This stack-based isolation is what makes recursion work correctly—each level of the problem maintains its own state without interfering with others.

Key Takeaway: Every recursive call creates a new stack frame with isolated copies of parameters and local variables, allowing multiple "versions" of the function to execute simultaneously without conflict.