C Storage Classes
Storage classes determine a variable's scope, lifetime and visibility across a program. C provides four storage class specifiers: auto, register, static, and extern.
Understanding storage classes helps control whether a variable is temporary, persists between function calls, or is shared across multiple source files.
static type name;
extern type name;auto and register
auto is the default for local variables (rarely written explicitly). register suggests to the compiler that a variable should be stored in a fast CPU register, though the compiler may ignore this hint.
static and extern
static inside a function makes a variable retain its value between calls. static at file scope limits a variable or function's visibility to that file. extern declares a variable defined in another file, allowing it to be shared.
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("%d\n", count);
}
int main() {
counter();
counter();
counter();
return 0;
}1
2
3static preserves count's value between calls instead of resetting it each time.
// file1.c
int sharedValue = 100;
// file2.c
#include <stdio.h>
extern int sharedValue;
int main() {
printf("%d\n", sharedValue);
return 0;
}100extern lets file2.c access a variable actually defined in file1.c.
Key points
- auto is the default storage class for local variables.
- static preserves a local variable's value between function calls.
- static at file scope restricts visibility to that file only.
- extern shares a variable's definition across multiple source files.
