Storage Classes in C Programming (Complete Guide with Examples)
This tutorial explains storage classes in C, which determine scope, lifetime, and visibility of variables. It covers auto, register, static, and extern with practical examples to help beginners understand memory management and variable accessibility.
1. What are Storage Classes
- Storage classes define:
- Scope: Where a variable is accessible
- Lifetime: How long a variable exists in memory
- Visibility: Where it can be used in the program
- C supports four main storage classes:
autoregisterstaticextern
2. auto Storage Class
- Default for local variables
- Stored in stack memory
- Lifetime: function execution
- Scope: within the block
Example:
Output:
3. register Storage Class
- Suggests compiler to store variable in CPU register for faster access
- Only for local variables of small size (int, char)
- Cannot take address using &
Example:
Output:
4. static Storage Class
- Local
staticvariable retains its value between function calls - Default initial value is 0 if not assigned
- Can also be global static to limit scope to the file
Example:
Output:
Explanation:
- Value of
countis retained between calls
5. extern Storage Class
- Refers to variables declared in another file or outside function
- Scope: global
- Lifetime: entire program execution
Example:
Output:
Explanation:
externallows access to global variable x in multiple functions
6. Key Points to Remember
- auto: default local, stack memory
- register: fast access, local only
- static: retains value, local or file scope
- extern: global variable access across files/functions
- Storage classes help manage scope, lifetime, and memory efficiently