Language 1 of 10 · Topic 0.3

Variables, Scoping & Storage Classes (auto, static, extern, volatile)

1Concept

C variable scoping is block-based {}. Storage duration classes define variable lifetime and visibility: 1. auto: Default local stack variable (discarded when block exits). 2. static (local): Retains value across function calls in Data Segment. 3. static (global): Restricts visibility strictly to current translation unit (.c file). 4. extern: References a global variable defined in another .c file. 5. const: Read-only variable. 6. volatile: Prevents compiler optimization for memory-mapped hardware I/O registers.

2Architecture Diagram

[Stack Frame]       --> auto local variables (reallocated on every call)
[Data/BSS Segment]  --> static local & global variables (persist entire program runtime)
[Text Segment]      --> const literal constants (read-only memory)

3Code Example

Stage 0 Language Foundations
#include <stdio.h>

void counter_demo(void) {
    auto int local_var = 1;     // Reallocated on stack every invocation
    static int static_var = 1;  // Stored in Data Segment, persists across calls

    printf("local: %d | static: %d\n", local_var, static_var);
    local_var++;
    static_var++;
}

int main(void) {
    printf("Call 1: "); counter_demo();
    printf("Call 2: "); counter_demo();
    printf("Call 3: "); counter_demo();
    return 0;
}

4Expected Output

Call 1: local: 1 | static: 1
Call 2: local: 1 | static: 2
Call 3: local: 1 | static: 3

5Key Takeaways

  • static local variables are initialized only once when the program loads.
  • static global functions/variables prevent namespace pollution across C files.
  • volatile tells the optimizer that the variable value can change outside program control.