A Storage Class defines the scope (visibility), lifetime, and default initial value of a variable. It tells the compiler where to store the variable and how long it should stay in memory.
1. Automatic (auto)
This is the default for all local variables. You rarely need to type the keyword auto.
void func() {
int x = 10; // Same as 'auto int x = 10;'
}2. Register (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 used frequently (like loop counters).
Note: You cannot get the memory address (
&) of a register variable because it doesn't live in RAM.
3. Static (static)
Static variables are unique. They are initialized only once and they "remember" their value even after the function finishes.
#include <stdio.h>
void counter() {
static int count = 0; // Initialized only once
count++;
printf("Count: %d\n", count);
}
int main() {
counter(); // Prints 1
counter(); // Prints 2
counter(); // Prints 3
return 0;
}Expected Output:
Count: 1
Count: 2
Count: 34. External (extern)
The extern keyword is used to access a variable defined in a different file. It tells the compiler: "The variable exists, but you'll find it elsewhere."
// File1.c
int globalVar = 100;
// File2.c
extern int globalVar; // Points to the variable in File1.cWhy Use Storage Classes?
Memory Management: Use
autofor temporary data to keep the Stack clean.Performance: Use
registerfor high-frequency variables in time-critical loops.Data Persistence: Use
staticwhen you need a function to have a "memory" without using a messy global variable.Modular Programming: Use
externto share data across multiple.cfiles in large projects.