C Storage Classes – Explained with Syntax, Examples & Best Practices
In C, storage classes define the scope, visibility, and lifetime of variables and/or functions. They determine where variables are stored, how long they exist, and who can access them.
Types of Storage Classes in C
Storage Class | Keyword | Scope | Lifetime | Stored In |
---|---|---|---|---|
Automatic | auto | Local | Function block | Stack |
External | extern | Global | Entire program | Data segment |
Static | static | Local/Global | Entire program | Data segment |
Register | register | Local | Function block | CPU registers (if available) |
void func()
{
int a = 10; // automatic variable
printf("%d", a);
}
auto Storage Class
✅ Definition:
The default storage class for local variables inside functions.
✅ Syntax:
auto int x = 10;
✅ Example:
#include <stdio.h>
void show() {
auto int a = 5;
printf("Value of a: %d\n", a);
}
int main() {
show();
return 0;
}
extern Storage Class
✅ Definition:
Used to declare a global variable or function in another file.
✅ Syntax:
extern int count;
✅ Example:
File1.c
#include <stdio.h>
int count = 100;
File2.c
#include <stdio.h>
extern int count;
int main() {
printf("Count is: %d\n", count);
return 0;
}
static Storage Class
✅ Definition:
Preserves variable value even after the function exits.
✅ Syntax:
static int x = 1;
✅ Example:
#include <stdio.h>
void counter() {
static int count = 0;
count++;
printf("Count: %d\n", count);
}
int main() {
counter();
counter();
counter();
return 0;
}
✅ Output:
Count: 1 Count: 2 Count: 3
📌
static
also restricts the scope of global variables/functions to the current file.register Storage Class
✅ Definition:
Suggests storing variable in a CPU register for faster access.
✅ Syntax:
register int speed = 10;
✅ Example:
#include <stdio.h>
int main() {
register int i;
for(i = 0; i < 5; i++) {
printf("%d ", i);
}
return 0;
}
⚠️ You cannot use &
(address operator) with register variables.
Summary Table
Storage Class | Scope | Lifetime | Keyword | Use-Case |
---|---|---|---|---|
auto | Local | Function block | auto | Default local variable |
extern | Global | Entire program | extern | Access global var from other file |
static | Local/Global | Entire program | static | Persist value / limit visibility |
register | Local | Function block | register | Fast access, CPU-level variables |
Best Practices
Practice | Why It’s Important |
---|---|
Use static for caching values | Saves re-initialization overhead |
Use extern carefully | Avoid global clutter across files |
Prefer auto by default locally | Cleaner, no need to declare explicitly |
Use register sparingly | Modern compilers optimize this automatically |
Common Mistakes
Mistake | Consequence |
---|---|
Using register and trying &var | Compile-time error |
Overusing static everywhere | May increase memory footprint unnecessarily |
Declaring extern without defining | Linker error |