C Storage Classes
C Storage Classes
Storage classes in C define the scope, lifetime, and visibility of variables and functions within a program.
They tell the compiler:
β Where the variable is stored
β How long the variable exists (lifetime)
β Who can access it (scope)
β What is its default value
πΉ Available Storage Classes in C
| Storage Class | Scope | Lifetime | Default Value | Memory Location |
|---|---|---|---|---|
auto |
Local (block) | Function/block duration | Garbage value | Stack |
register |
Local | Function/block duration | Garbage value | CPU register (if available) |
static |
Local or Global | Entire program duration | Zero | Memory (Static/Data Segment) |
extern |
Global | Entire program duration | Zero | Memory (Static/Data Segment) |
1οΈβ£ auto (Automatic Storage)
-
Default for local variables
-
Exists only inside functions or blocks
-
Stored in stack memory
β Usually we donβt use auto keyword explicitly because itβs default.
2οΈβ£ register
-
Suggests storing variable in CPU register for faster access
-
Cannot take its memory address using
&
β Note: Compiler may ignore this request.
3οΈβ£ static
A static variable preserves its value between function calls.
β Example: Local static variable
Output:
πΉ Unlike normal local variables, static does not reset.
β Static Global Variable
A static global variable is accessible only inside the file, not from other .c files.
4οΈβ£ extern
extern is used to declare a variable that is defined in another file or location.
Useful in multi-file projects.
π Example
π file1.c
π file2.c
β extern does not allocate memory β it only references existing storage.
π§ Summary Table
| Keyword | Use Case |
|---|---|
auto |
Default local variable |
register |
Faster access storage suggestion |
static |
Persistent variable or file-level global variable |
extern |
Global variable sharing between files |
