In C, every variable has two attributes: a type (like int or float) and a storage class. A storage class defines the scope (visibility) and lifetime of a variable within a program.
Definition: Storage classes tell the compiler where to store the variable, what the initial value is, and how long the variable exists.
Before diving into specific specifiers, it is critical to understand three key concepts:
C provides four primary storage class specifiers:
| Specifier | Storage | Initial Value | Scope | Lifetime |
|---|---|---|---|---|
| auto | Stack (Memory) | Garbage | Local | Function Block |
| register | CPU Register | Garbage | Local | Function Block |
| static | Data Segment | Zero | Local/Global | Entire Program |
| extern | Data Segment | Zero | Global | Entire Program |
The auto storage class is the default for all local variables declared inside a function or block.
void function() {
int x; // same as "auto int x;"
}
The register specifier suggests to the compiler that the variable be stored in a CPU register instead of RAM for faster access.
register int counter;
The static storage class instructs the compiler to keep a local variable in existence during the entire lifetime of the program.
Unlike auto variables, static local variables maintain their values between function calls.
void increment() {
static int count = 0;
count++;
printf("%d", count);
}
// Calling increment() thrice will print 1, 2, 3.
When a function is declared as static, its scope is restricted to the file in which it is defined. This is used for encapsulation and data hiding.
The extern storage class is used to give a reference to a global variable that is visible to all the program files.
// File1.c
int count = 5;
// File2.c
extern int count; // Declares that count is defined elsewhere
void main() {
printf("%d", count);
}
The const qualifier is used to declare variables whose value cannot be changed after initialization.
const float PI = 3.14;
// PI = 3.15; // This will cause a compilation error
extern only when you want to access that variable in a different file.register like auto.const variable without initializing it immediately. Since you can't change it later, an uninitialized const is useless.static makes a variable accessible everywhere. A static local variable still has local scope; it just has a permanent lifetime.Q: Can I use 'extern' inside a function?
A: Yes, it tells the function that the variable it is using is a global one defined either later in the same file or in another file.
Q: What is the difference between 'static global' and 'global'?
A: A regular global variable can be accessed by other files using extern. A static global variable is hidden from other files.
Q: Why use 'const' instead of '#define'?
A: const variables have a data type and follow scope rules, making them safer and easier to debug than #define macros.