Storage Classes in C
In C programming, storage classes define how variables behave in terms of scope, lifetime and memory location.
Understanding storage classes is essential for writing efficient, predictable and well-structured programs.
Why Storage Classes Are Important
Storage classes help the compiler decide:
- Where the variable is stored in memory
- How long the variable exists
- Which parts of the program can access it
Types of Storage Classes
C provides four main storage classes:
- auto
- register
- static
- extern
1. auto Storage Class
The auto storage class is the default for local variables.
These variables:
- Are created when a function starts
- Are destroyed when the function ends
- Exist only inside the block where they are declared
void demo() {
auto int x = 10;
printf("%d", x);
}
In practice, programmers rarely write auto explicitly.
2. register Storage Class
The register keyword suggests that the variable should be stored
in a CPU register for faster access.
void counter() {
register int i;
for (i = 0; i < 5; i++) {
printf("%d ", i);
}
}
Important notes:
- The compiler may ignore the request
- You cannot get the address of a register variable
3. static Storage Class
The static keyword changes the lifetime of a variable.
A static variable:
- Is initialized only once
- Retains its value between function calls
- Exists for the entire program execution
void countCalls() {
static int count = 0;
count++;
printf("Count = %d\n", count);
}
Each call increases the value instead of resetting it.
4. extern Storage Class
The extern keyword is used to share variables across multiple files.
It tells the compiler that the variable is defined elsewhere.
// file1.c
int total = 100;
// file2.c
extern int total;
printf("%d", total);
This is common in large projects with multiple source files.
Real-World Usage
- auto – temporary variables inside functions
- register – loop counters in performance-critical code
- static – counters, configuration flags
- extern – shared data across modules
Quiz
Q1: Which storage class keeps a variable alive between function calls?
static
Q2: Which storage class allows sharing variables across files?
extern
Q3: Which storage class is default for local variables?
auto
Q4: Can we access the address of a register variable?
No
Q5: Does static variable reset after function ends?
No
Mini Practice
- Create a function that counts how many times it is called using
static - Declare a global variable and access it using
extern - Experiment with
registerinside a loop