In C, Storage Classes are used to define the scope (visibility), lifetime, and initial value of variables and functions. By telling the compiler where to store a variable and how long it should exist, you can write more memory-efficient and organized code.
C provides four primary storage classes, each serving a specific purpose in memory management:
| Storage Class | Storage Location | Default Value | Lifetime |
|---|---|---|---|
| auto | Stack (RAM) | Garbage | End of block |
| register | CPU Register | Garbage | End of block |
| static | Data Segment | Zero (0) | End of program |
| extern | Data Segment | Zero (0) | End of program |
The auto storage class is the default for all local variables. It is rarely written explicitly because variables declared inside a function are automatically "auto."
A static variable remains in memory until the program ends. If declared inside a function, it "remembers" its value between different function calls.
The register keyword suggests to the compiler that the variable be stored in a CPU register instead of RAM for faster access. This is used for variables used frequently, like loop counters.
The extern storage class is used when a variable is defined in one file but needs to be accessed in another. It tells the compiler, "This variable exists somewhere else."
static keyword for global variables that you don't want other files to access. This is known as "Internal Linkage" and is a great way to keep your code modular and private!