The C Language

scope and lifetime

Two different questions get asked about every name in a program. First: where in the source text am I even allowed to write this name? That is scope — like which rooms of a building a particular keycard opens. Second: for how long does the actual storage behind the name exist while the program runs? That is lifetime — like how long the room itself stays rented. They sound similar but they are not the same question, and confusing them causes real bugs.

Scope is about visibility in the code. A variable declared inside a function or a { } block has block scope: it is visible only from its declaration to the end of that block, and a name inside an inner block can hide one with the same name outside it. A name declared outside all functions has file scope: visible to the rest of that file. Lifetime (storage duration) is about the runtime. A typical local variable has automatic storage duration: its storage is created when the block is entered and destroyed when the block exits. A variable marked static, or one at file scope, has static storage duration: it lives for the entire run of the program.

Why the difference bites: a local variable can be in scope on one line and gone on the next — and returning the address of such a variable, or keeping a pointer to it after its block ends, gives a dangling pointer to storage that no longer exists. A static local, by contrast, keeps its value between calls even though its name is only visible inside the function. Keeping scope (a compile-time idea) and lifetime (a runtime idea) clearly apart is the key to reasoning about C correctly.

int g = 1; /* file scope, lives whole program */ void f(void) { int local = 2; /* block scope, auto: gone at } */ static int calls = 0; /* block scope, but lives forever */ calls++; /* remembers its value across calls */ }

local and calls are both only visible inside f (same scope), but local dies at the closing brace while calls persists for the whole program (different lifetime).

Scope is compile-time visibility; lifetime is runtime existence — they are independent. Returning a pointer to a local variable, or using it after its block ends, dereferences storage that no longer exists (a dangling pointer).

Also called
visibility and storage duration可見範圍生命週期