Storage Classes (Lesson)
Storage Classes in C
Storage classes define the scope (visibility) and lifetime of variables and/or functions within a C program.
12.1 The Four Storage Classes
| Storage Class | Keyword | Storage | Initial Value | Scope | Lifetime |
|---|---|---|---|---|---|
| Automatic | auto | RAM | Garbage | Local | Within block |
| Register | register | Register | Garbage | Local | Within block |
| Static | static | RAM | Zero | Local | Till end of program |
| External | extern | RAM | Zero | Global | Till end of program |
12.2 auto
The default storage class for all local variables.
auto int age; // Same as 'int age;'
12.3 register
Directs the compiler to store the variable in a CPU register instead of RAM for faster access. Used for highly-accessed variables like loop counters.
- Note: You cannot get the address of a register variable using
&.
register int counter;
12.4 static
A static local variable retains its value even after the function exits. It is initialized only once.
void count() {
static int x = 0;
x++;
printf("%d ", x);
}
// Calling count() three times prints: 1 2 3
12.5 extern
Used to give a reference to a global variable that is visible to all program files. When you use extern, the variable is not initialized because the name points to a location previously defined.
// File1.c
int count = 5;
// File2.c
extern int count;
void printCount() { printf("%d", count); }
Practical Example: Static inside a loop
#include <stdio.h>
void func() {
static int i = 1; // initialized only once
int j = 1; // initialized every time
printf("static=%d, auto=%d\n", i, j);
i++;
j++;
}
int main() {
func();
func();
func();
return 0;
}
/**
Output:
static=1, auto=1
static=2, auto=1
static=3, auto=1
**/
Check the Lecture Slides for detailed performance benchmarks of register vs RAM storage.