Back to series
· 10 min read

Variable Scope and Lifetime


1. What Are Variable Scope and Lifetime?

Variable scope and lifetime are two closely related concepts in programming languages, but they must not be conflated.

Scope: defines the region of code in a program where a variable name can be accessed or referenced.

Lifetime: defines the time range during which a variable or object exists from creation to destruction, or from when it becomes valid until it ceases to be valid.

A simple way to think about it:

  • Scope answers: Where can this name be accessed?
  • Lifetime answers: When does this object exist?

For example, in C:

#include <stdio.h>

int main() {
    int value = 100;

    {
        int number = 200;
        printf("%d\n", number);
    }

    printf("%d\n", value);

    return 0;
}

value is visible throughout the body of the main function, while number is visible only in the inner block.

In common implementations, the storage duration of both local variables follows the automatic storage duration rules during program execution, but their name scopes are different.

1.1 The Difference Between Scope and Lifetime

Comparison Dimension Scope Lifetime
Core meaning Visible range of the name Valid existence time of the object or variable
Focus Identifiers, name binding Objects, storage, resources
Main determining factors Code structure, language scope rules Storage duration, object creation and destruction rules
Typical boundaries Code blocks, functions, modules, classes Creation, construction, destruction, program termination
Main impact Whether the name can be accessed directly Whether the object can be used safely
Common issues Name shadowing, undefined names Dangling references, resource leaks, premature destruction

The two do not always change in sync.

For example, in C++, a dynamically allocated object can be accessed through a pointer. Even if the local pointer variable used to create the object has gone out of scope, the object can still exist as long as it has not been freed.

int* create() {
    int* ptr = new int(100);
    return ptr;
}

int main() {
    int* value = create();

    // The ptr in create has gone out of scope
    // But the dynamic object it points to still exists

    delete value;
    return 0;
}

Here:

  • The scope of ptr ends, and the local pointer variable is no longer visible.
  • The lifetime of ptr ends.
  • The integer object created by new still exists.
  • After delete executes, the lifetime of the dynamic object ends.

This is a key example for understanding the difference between scope and lifetime.


2. Main Types of Variable Scope

Different languages classify scope somewhat differently. Common categories include block scope, function scope, local scope, global scope, and module scope.

2.1 Block Scope

Block scope is usually delimited by a pair of braces or another code-block structure.

In C:

#include <stdio.h>

int main() {
    int outer = 10;

    {
        int inner = 20;

        printf("%d\n", outer);
        printf("%d\n", inner);
    }

    printf("%d\n", outer);

    // printf("%d\n", inner); // Error: inner is not in the current scope

    return 0;
}

An inner block can access variables visible in the outer block, but the outer block cannot directly access local variables declared in the inner block.

Scope structure:

flowchart TB
    A["main function scope"] --> B["declare outer"]
    A --> C["inner block"]
    C --> D["declare inner"]
    C --> E["can access outer"]
    C --> F["can access inner"]
    A --> G["inner block ends"]
    G --> H["inner name not visible"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Block scope is commonly used to:

  • Limit the visibility of temporary variables.
  • Avoid variable names polluting external code.
  • Narrow the range in which local variables are used.
  • Work with RAII to manage resource lifetimes.

2.2 Function Scope

Function scope means different things in different languages, so you cannot simply assume that all variables inside a function have function scope.

For example, in C, labels (the identifiers used by goto) have function scope, while ordinary local variables usually have block scope.

void test() {
    int value = 100;

label:
    value++;

    if (value < 105) {
        goto label;
    }
}

Here, label can be referenced anywhere in the function, while value still follows the scope rules of the block it is in.

In languages such as Python, function scope usually refers to the namespace rules governing the local names created by assignment inside a function body.

2.3 Local Scope

A local variable is a variable declared inside a function, method, or code block.

public void calculate() {
    int result = 100;

    System.out.println(result);
}

result can only be accessed directly within its local scope.

Local variables are commonly used to:

  • Hold temporary computation results.
  • Manage state inside a function.
  • Reduce variable coupling between different functions.
  • Avoid the side effects of global state.

Note that the scope of a local variable and its storage location are not the same concept. Local variables are not necessarily all stored on the stack; the actual location is determined by the language implementation, compiler optimizations, and the runtime.

2.4 Global Scope

Global variables are usually declared outside functions or classes and can be accessed over a broader range of the program.

C:

#include <stdio.h>

int globalValue = 100;

void printValue() {
    printf("%d\n", globalValue);
}

int main() {
    printValue();
    return 0;
}

Global variables usually have static storage duration, meaning their storage persists for the entire execution of the program.

Advantages:

  • Multiple functions can share data.
  • Suitable for holding program-level configuration or shared state.
  • No need to pass them through multiple layers of function parameters.

Disadvantages:

  • Increase coupling between modules.
  • Tend to create implicit dependencies.
  • May lead to data races in multithreaded environments.
  • Make testing and maintenance harder.

Large projects generally prefer to minimize mutable global state, managing shared data through parameter passing, object encapsulation, or dependency injection.

2.5 Module Scope

Module scope is a common organizing mechanism in modern programming languages.

For example, JavaScript:

const appName = "Reverie";

function start() {
    console.log(appName);
}

export { appName, start };

appName and start are visible inside the current module and are exposed to other modules through export.

Module scope can:

  • Limit the visibility of names.
  • Reduce global naming conflicts.
  • Isolate a module's internal implementation.
  • Make dependencies between modules explicit.

Module rules differ between languages. For example, JavaScript uses a module import/export mechanism, Python uses module namespaces, and Rust uses a module tree with visibility rules.


3. Lexical Scope and Dynamic Scope

Scope determines not only where a variable is visible, but also which variable a name reference ultimately binds to.

The common scope rules are lexical scope and dynamic scope.

3.1 Lexical Scope

Lexical scope is also called static scope.

The binding relationship of a variable is mainly determined by the nesting structure in the source code, not by where the function is called from at runtime.

JavaScript example:

const value = "global";

function outer() {
    const value = "outer";

    function inner() {
        console.log(value);
    }

    return inner;
}

const fn = outer();

fn(); // outer

inner is defined inside outer, so it can access value from the outer scope at its definition location.

Even if inner is called after outer has finished executing, it can still access the corresponding lexical environment.

Name lookup process in lexical scope:

flowchart TB
    A["Access variable name"] --> B{"Does it exist in the current lexical scope?"}
    B -->|"Yes"| C["Use binding in current scope"]
    B -->|"No"| D["Look up outer lexical scope"]
    D --> E{"Is a binding found?"}
    E -->|"Yes"| F["Use outer binding"]
    E -->|"No"| G["Continue searching outward"]
    G --> H{"Reached the top of the scope chain?"}
    H -->|"No"| D
    H -->|"Yes"| I["Name resolution fails"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Lexical scope is the primary name-binding model used by mainstream languages such as JavaScript, Python, C, C++, Java, Go, and Rust.

3.2 Dynamic Scope

Dynamic scope determines variable binding based on the function call chain.

In other words, the meaning of a variable may depend on where the current function was called from.

This can be understood with pseudocode:

variable value = "global"

function outer:
    variable value = "outer"
    call inner

function inner:
    print value

call outer

Under dynamic scope rules, when inner looks up value, it searches along the runtime call chain, so it may get outer.

Under lexical scope, however, inner's variable binding is determined by its definition location.

Dynamic scope is rarely the default rule in modern general-purpose programming languages, but some language features, macro systems, dynamic variable mechanisms, or special execution environments may provide similar behavior.

3.3 Differences Between the Two Scopes

Comparison dimension Lexical scope Dynamic scope
Basis for name binding Definition location in source code Runtime call chain
Variable lookup method Search along lexical nesting structure Search along dynamic calling environment
Result predictability Generally high Depends on call path
Compile-time analysis Easier Usually more complex
Common languages JavaScript, Python, C, C++, Java, Rust A few languages or special mechanisms

4. Variable Shadowing

Variable shadowing means that an inner scope declares a variable with the same name as one in an outer scope, so that name references in the inner code bind preferentially to the inner variable.

4.1 Basic Variable Shadowing

let value = 100;

function test() {
    let value = 200;

    console.log(value); // 200
}

test();

console.log(value); // 100

The inner value shadows the outer value, but the two variables are not the same object or binding.

4.2 Shadowing in Nested Scopes

#include <iostream>

int main() {
    int value = 10;

    {
        int value = 20;

        std::cout << value << std::endl; // 20
    }

    std::cout << value << std::endl; // 10

    return 0;
}

After the inner code block ends, the inner variable is no longer in visible scope, and the outer name becomes the currently visible binding again.

4.3 Differences Between Shadowing and Assignment

Shadowing creates a new name binding, while assignment modifies the value of an existing variable.

let value = 10;

function test() {
    value = 20; // modifies the outer variable
}

test();

This differs from the following code:

let value = 10;

function test() {
    let value = 20; // creates a local variable, shadowing the outer variable
}

4.4 Shadowing Rules in Different Languages

Different languages impose different restrictions on declaring variables with the same name.

Language Common Rules
C Inner code blocks can declare local variables with the same name
C++ Inner scopes can shadow outer names
Java Local variables cannot be freely redeclared to shadow certain outer local variables
JavaScript let and const support block-level shadowing; var has function scope
Python Assignment inside a function usually creates a local name, unless global or nonlocal is used
Go Supports short variable declarations to create new bindings in specific scopes, making same-name shadowing easy to occur
Rust Supports variable shadowing and allows redeclaring variables with the same name

Variable shadowing can improve code locality when used appropriately, but overuse increases reading and debugging costs.


5. Variable Lifetime and Storage Duration

Lifetime describes when a variable or object exists and when it ceases to be valid.

In C and C++, it is particularly important to distinguish storage duration from scope.

Storage duration determines how long an object's storage lasts, while scope determines the visibility range of a name.

5.1 Automatic Storage Duration

Automatic storage duration is usually used for local variables.

void calculate() {
    int value = 100;
}

When the program enters the corresponding code block and executes the variable definition, the variable's lifetime begins; when it leaves the corresponding code block, the lifetime of an object with automatic storage duration ends.

Typical characteristics:

  • Lifetime is usually tied to execution of the code block.
  • Ordinary local variables do not need to be manually released.
  • Common implementations use stack frames to manage the relevant storage.
  • They may be optimized into registers or eliminated entirely by the compiler.

5.2 Static Storage Duration

Objects with static storage duration persist throughout the entire execution of the program.

C:

#include <stdio.h>

int globalValue = 100;

void counter() {
    static int count = 0;

    count++;

    printf("%d\n", count);
}

int main() {
    counter();
    counter();
    counter();

    return 0;
}

Output:

1
2
3

The name scope of count is inside the counter function, but it has static storage duration.

This shows that:

Local scope does not mean a short lifetime.

Characteristics of static local variables:

  • The name is visible only inside the function.
  • The storage duration covers the entire program execution.
  • The previous value is retained across multiple calls to the function.
  • Initialization rules depend on the language standard.

5.3 Dynamic Storage Duration

Objects with dynamic storage duration are created through dynamic memory management mechanisms, and their lifetime is determined by the program or by runtime resource management rules.

C++:

int* create() {
    int* ptr = new int(100);
    return ptr;
}

int main() {
    int* value = create();

    delete value;

    return 0;
}

A dynamic object is not automatically destroyed just because the function that created it returns.

Its lifetime usually begins when object creation completes and ends when the object is destroyed.

5.4 Thread Storage Duration

Objects with thread storage duration are related to the thread's lifetime.

C++:

thread_local int threadValue = 0;

Each thread has its own threadValue instance. The object is typically created after the thread begins execution and performs the relevant initialization, and is destroyed when the thread ends.

Applicable to:

  • Thread-local state.
  • Per-thread caches.
  • Thread context data.
  • Avoiding direct sharing of certain mutable state among multiple threads.

5.5 Summary of the Four Storage Durations in C++

Storage Duration Lifetime Common Declaration Form
Automatic storage duration During execution of the relevant code block Ordinary local variables
Static storage duration During the entire program execution Global variables, static variables
Dynamic storage duration From dynamic creation to destruction new, dynamic allocation
Thread storage duration Thread lifetime thread_local

Note: this is C++'s classification of storage duration. Other languages may use different terminology and object lifetime models.


6. How Scope and Lifetime Combine

Scope and lifetime are independent of each other, but in real programs they produce a variety of combinations.

6.1 Local Scope and Automatic Storage Duration

void test() {
    int value = 100;
}
  • Name scope: the current function's code block.
  • Storage duration: automatic storage duration.
  • Lifetime: typically ends when the code block exits.

This is the most common local variable pattern.

6.2 Local Scope and Static Storage Duration

void counter() {
    static int count = 0;
    count++;
}
  • Name scope: the current function.
  • Storage duration: static storage duration.
  • Lifetime: the entire program execution.

The name is visible only within the local scope, but the corresponding object persists for a long time.

6.3 Local Pointers and Dynamic Objects

int* create() {
    int* ptr = new int(100);
    return ptr;
}
  • ptr: a local name with local scope.
  • The pointer object corresponding to ptr: automatic storage duration.
  • The integer object created by new: dynamic storage duration.
  • After the function returns: the local pointer object's lifetime ends, while the dynamic integer object still exists.

6.4 External References and Object Lifetime

int& create() {
    int value = 100;
    return value;
}

After the function returns, value's lifetime has already ended, and the returned reference loses its valid target.

This is a classic lifetime error.

6.5 Summary of Combinations

Scenario Name Scope Object Storage Duration Typical Case
Ordinary local variable Local Automatic Variable inside a function
Static local variable Local Static static variable inside a function
Global variable File or globally related scope Static Global state
Dynamic object Accessed via pointer or reference Dynamic Object created by new
Thread-local variable Determined by declaration location Thread thread_local

Understanding these combinations helps avoid mistaking the visible range of a variable name for the actual time the object exists.


7. Closures and Lifetime

Closures are an important concept for understanding scope and lifetime.

A closure generally refers to the structure formed by combining a function with the external lexical environment it captures.

7.1 Basic Concept of Closures

JavaScript:

function createCounter() {
    let count = 0;

    return function() {
        count++;
        return count;
    };
}

const counter = createCounter();

console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

After createCounter finishes executing, its function call has already returned, yet the inner function can still access count.

This is because the closure retains the ability to access the external lexical environment.

7.2 Why Can Closures Access External Variables?

After an ordinary function call ends, its local execution environment no longer exists as an active call frame.

But if an inner function still references external variables, the runtime must ensure those variables remain available for subsequent calls.

Therefore, the runtime may retain the bindings in the relevant lexical environment.

The relationship of closures: