← Previous | 🏠 Homepage | Next Chapter → |
Storage Classes – Where Variables Live & How Long
Auto
Lives in: Memory
Starts with: Garbage value
Scope: Inside the block
Life: Until block ends
Lives in: Memory
Starts with: Garbage value
Scope: Inside the block
Life: Until block ends
Register
Lives in: CPU Register (if available)
Faster access (good for loop counters!)
Starts with: Garbage
Can’t store float
or double
Lives in: CPU Register (if available)
Faster access (good for loop counters!)
Starts with: Garbage
Can’t store float
or double
Static
Lives in: Memory
Starts at: 0
Scope: Local
Life: Lives forever (retains value across function calls)
Use when value must be remembered between calls
Lives in: Memory
Starts at: 0
Scope: Local
Life: Lives forever (retains value across function calls)
Use when value must be remembered between calls
External Storage Class (extern
)
Where it lives: Memory
Default value: 0
Scope: Global — available to all functions
Lifetime: As long as the program is alive
Global Variables
Variables declared outside all functions are global. That means any function can use them — no permission slip needed!
Example:
int i;
main() {
printf("%d", i); // prints 0
increment();
decrement();
}
increment() { i++; }
decrement() { i--; }
Result?
The same i
is used and updated by all functions. One big happy variable family.
extern int y;
vs int y = 31;
-
extern int y;
→ Just tells the compiler “Hey, y exists somewhere!” -
int y = 31;
→ This actually creates y and gives it a home (in memory).
A variable can be declared (extern
) many times but defined (int y = 31;
) only once.
Local vs Global Name Clash
int x = 10;
main() {
int x = 20;
printf("%d", x); // prints 20 (local wins!)
display();
}
display() {
printf("%d", x); // prints 10 (global x)
}
One Last Thing About static
Globals
If you write:
static int count;
outside all functions — it acts like extern
, but only within the same file. So it’s a private global — like a secret agent
When to Use Which Storage Class?
Here’s your cheat sheet for smart C programming:
Storage Class | Use It When... |
---|---|
auto |
You just need a variable for temporary work. Like a sticky note — use and throw. |
register |
You need speed — loop counters or frequently accessed stuff. Just remember, CPU registers are few, so don’t overdo it! |
static |
You want to remember a value between function calls. Like a goldfish with memory — but better. |
extern |
You want one variable that everyone in the program can use, across functions and even files. Like a public notice board. |
Pro Tips:
-
Don't spam
register
or you'll run out of CPU registers. -
Don’t declare everything
extern
— wastes memory. -
Use
static
only when you need to remember stuff between function calls. -
Most of the time,
auto
is just perfect. Simple. Clean. Done.
No comments:
Post a Comment