Scope and lifetime of variables are among the key aspects of C program structure. Scope is the part of the code where a variable is accessible by name. Lifetime defines when a variable actually exists in memory.
Background
C was designed for low-level control, thus providing a flexible but dangerous approach to scope and lifetime through the classification of variables by declaration place (block, file, global, static).
Problem
Misunderstanding of scope/lifetime leads to classic bugs: attempts to access unavailable or already destroyed variables (use-after-free), name conflicts between global and local variables (shadow variables), unintentional changes to global variables.
Solution
Explicitly define the needed storage type (auto, static, extern), wisely use block scope, minimize the number of global variables, and clearly differentiate between stack and non-stack lifetime.
Example code:
int global_var; // Global, lives for the entire runtime void func() { int local_var = 5; // Automatic, lives within func() static int stat_var = 0; // Static, lives between calls stat_var++; }
Key features:
What happens if you declare two variables with the same name in different blocks?
The inner variable will shadow the outer one (shadow variable). This can lead to unexpected errors.
int x = 10; ... if (1) { int x = 50; printf("%d", x); // prints 50, global x is hidden }
What is the lifetime of an automatic variable defined inside a function?
It exists only during the function call. After exit, the memory is freed, and the value is lost.
Can a static local variable be used outside the function where it was declared?
No, its scope is only within the function. It is not visible from outside, despite having a lifetime that lasts for the entire program execution.
void f() { static int x = 0; } // Not accessible outside f()
static vs auto).A novice developer creates a counter inside a loop as static, and this counter "accumulates" values between iterations, although it was expected to reset each time.
Pros:
Cons:
A developer uses static strictly for caching, and for temporary needs — regular auto variables.
Pros:
Cons: