Storage Classes & Scope
Two variables with the same name can behave completely differently depending on where they live, how long they live, and which file can see them.
In plain English
Storage classes decide where a variable lives, how long it stays, and who can see it.
Scope, lifetime, and linkage
Scope is where a name is visible. Lifetime is how long its storage exists. Linkage describes whether other translation units can refer to it. A local variable inside a function has block scope and automatic lifetime by default. A global variable has file scope and static lifetime. These three ideas make the storage-class keywords predictable.
auto, register, static, and extern
auto is the default for local variables. register is a hint that a variable should be kept in a CPU register if possible. Modern compilers ignore it when they have better information. You cannot take the address of a register variable. A static local keeps its value between calls while remaining invisible outside the function. A static global is private to its file. extern declares a name defined elsewhere.
int next_id(void) {
static int id = 0; /* initialized once */
return ++id;
}
/* file a.c */
int shared_value = 42;
/* file b.c */
extern int shared_value;Key takeaways
- auto is the default local storage class.
- register is only a hint and forbids taking the address.
- static locals persist across calls but stay block-scoped.
- static globals are private to their translation unit.
- extern declares a name defined in another translation unit.
Common pitfalls
- Thinking static means constant.
- Taking the address of a register variable.
- Defining the same external variable in multiple files.
- Assuming a static local is reinitialized on every call.
Key focus
- Predict the output of a function with a static local called multiple times.
- Know the difference between a declaration and a definition.
Quick check
1. What does a static local variable preserve between function calls?
2. Which keyword declares a variable defined in another translation unit?