CC Explainer
C · 1 · Foundations4 / 35 · 11%

Storage Classes & Scope

auto, static, extern, register — who owns a variable, and for how long.

Examples: static, extern, const, scope rules

shortcuts: ← prev · → next · M mark
1

Automatic Storage

Locals live on the stack and die when the block exits.

Example
example
void f(void) {
    int x = 1;      // automatic: created on entry
    {
        int y = 2;  // inner block scope
    }               // y destroyed here
}                   // x destroyed here
main()ret, args, localsfoo(int)ret, args, localsbar()ret, args, localstop ↑
one frame per call
2

static — Lifetime vs Visibility

static means two different things depending on where you write it.

Example
example
static int counter = 0;   // file scope: private to this .c file

void tick(void) {
    static int calls = 0; // block scope: persists across calls
    calls++;
}
At file scope static = internal linkage. Inside a function static = permanent lifetime.
3

extern & Headers

extern declares a symbol defined in another translation unit.

Example
example
// config.h
extern int g_verbose;   // declaration only

// config.c
int g_verbose = 0;      // the single definition
WATCH OUT
Defining a global in a header (without extern) causes duplicate-symbol link errors.
4

const & Shadowing Pitfalls

Constants and the scoping traps that hide bugs.

Example
example
const double PI = 3.14159;   // read-only object
int x = 1;
void f(void) {
    int x = 2;   // shadows the global — the global is unreachable here
}
Common pitfalls
  • ✕Shadowing a global with a local of the same name — compile with -Wshadow.
  • ✕Assuming a static local resets between calls. It does not.
  • ✕Using const on a pointer without deciding which side it protects.