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

Stack-Based Lifetime for Local Variables

How local variables are created when a function is called and destroyed when it returns.

Stack-Based Lifetime for Local Variables

What you'll learn: How local variables are created when a function is called and destroyed when it returns.


The Core Idea

When you call a function, the computer needs a place to store that function's local variables. It uses a special memory region called the stack. Think of it like a stack of cafeteria trays: each function call adds a new tray on top, and when the function finishes, that tray gets removed.

When a function is called:

  1. A new "stack frame" is created for that function
  2. All local variables are allocated space in this frame
  3. The function executes using these variables

When the function returns:

  1. The entire stack frame is removed
  2. All local variables in that frame are destroyed
  3. Their memory is freed automatically

Why This Matters

This automatic creation and destruction is why local variables only exist during the function's execution. Once the function returns, trying to access those variables would be meaningless—they're gone!

Analogy: Imagine each function call is a meeting. When the meeting starts, everyone gets a temporary notepad (local variables). You can write notes during the meeting. When the meeting ends, all notepads are collected and destroyed. If you want to keep information, you must return it before leaving.

This stack-based approach is efficient because:

  • Memory allocation/deallocation is automatic
  • No need to manually clean up local variables
  • Memory is reused as functions call and return

Key Takeaway: Local variables live on the stack and are automatically created when their function is called and destroyed when it returns—their lifetime is tied directly to the function's execution.