In C programming, Storage Classes define the scope (visibility), lifetime, and location of a variable. They tell the compiler where to store the variable, what its initial value will be, and how long it should stay in the computer's memory.
There are four primary storage classes in C:
1. auto (Automatic)
This is the default storage class for all local variables.
- Storage: RAM (Stack).
- Initial Value: Garbage value (random data).
- Scope: Local to the block
{ }where it is defined. - Lifetime: Destroyed when the block is exited.
void function() {
auto int x = 10; // 'auto' is optional, 'int x = 10' is the same.
}2. register
This is a hint to the compiler to store the variable in a CPU Register instead of RAM for lightning-fast access. It is used for variables that are used very frequently (like loop counters).
- Storage: CPU Register.
- Note: You cannot get the memory address (
&) of a register variable because it doesn't live in RAM.
for (register int i = 0; i < 1000; i++) {
// fast access to i
}3. static
A static variable is initialized only once and retains its value even after the function call ends. It is not destroyed when the block is exited.
- Storage: RAM (Data Segment).
- Initial Value: Zero (0).
- Lifetime: Persists until the end of the program.
void count() {
static int c = 0;
c++;
printf("%d ", c);
}
// Calling count() three times prints: 1 2 34. extern (External)
This is used to give a reference to a global variable that is visible to all files in a program. It is used when you have multiple files and want to share a variable.
- Storage: RAM (Data Segment).
- Initial Value: Zero (0).
- Scope: Global (can be accessed anywhere).
// File 1.c
int globalVar = 5;
// File 2.c
extern int globalVar; // Tells compiler to look for it in another fileSummary Table for Quick Reference
| Storage Class | Location | Initial Value | Scope | Lifetime |
auto | Stack | Garbage | Local | End of block |
register | CPU Register | Garbage | Local | End of block |
static | Data Segment | Zero | Local | End of program |
extern | Data Segment | Zero | Global | End of program |
Key Takeaway
- Use
autofor normal tasks. - Use
staticwhen you need a variable to "remember" its value. - Use
registerfor extreme performance in loops. - Use
externfor large projects with multiple files.
