Storage Classes, Variable Scope & Linkage Dynamics
“auto, register, static, and extern lifetime, memory segments, and linkage rules.”
1.The Four C Storage Classes & Memory Segments
§ 1.1.Every variable in C possesses two essential attributes: Scope (where the variable is visible) and Lifetime / Storage Duration (how long its memory remains allocated):
1. auto (Automatic):
- Default for local variables declared inside a block or function.
- Allocated on the Stack segment when the block is entered; deallocated on block exit. Default value is garbage.
2. register:
- Suggests the compiler store the variable in a fast CPU register instead of RAM.
- Cannot take address using & (e.g. ®_var is a compilation error!).
3. static:
- Local static: Scope is confined to the declaring block, but lifetime persists throughout the entire program run in the Data / BSS Segment. Initialized strictly ONCE at startup (defaults to 0).
- Global static: Restricts visibility (internal linkage) strictly to the current .c compilation unit.
4. extern:
- Declares a variable defined in another file (external linkage). Allocates zero new memory; simply informs the linker.
2. GATE Worked Numerical: Static Scope & Variable Shadowing
Inner block declarations SHADOW outer block declarations with the same name. Static variables retain their value across function calls, but local automatic variables re-initialize every call!
Consider the code:
int x = 10; // global
void print_val() {
static int x = 5;
int y = 5;
x += 2;
y += 2;
printf("%d %d ", x, y);
}
int main() {
print_val();
print_val();
return 0;
}
Trace output:
Call 1:
static int x initialized to 5. x += 2 -> x = 7.
auto int y initialized to 5. y += 2 -> y = 7.
Prints: '7 7 '.
Call 2:
static int x retains previous value 7! x += 2 -> x = 9.
auto int y is re-created on stack and initialized to 5! y += 2 -> y = 7.
Prints: '9 7 '.
Total Output: '7 7 9 7 '.
Primary Academic References & Exam Sources
Every concept in Notes From a B.Tech Brain is synthesized from authoritative academic texts, seminal peer-reviewed research, verified exam archives, and renowned university lectures.
Curated for clarity, rigorous numerical solving, and semester excellence:
Systematic beginner-to-advanced C with clear examples.
Clear step-by-step C explanations — great for semester lab preparation.