Storage Classes in C: Definition, Examples, and Usage
storage classes define the scope, lifetime, and visibility of variables and functions. They control where variables are stored and how long they exist during program execution. Common storage classes include auto, register, static, and extern.How It Works
Storage classes in C are like labels that tell the computer where to keep a variable and how long it should remember it. Imagine you have a notebook where you write notes. Some notes you write just for today and then erase (temporary), while others you keep for a long time (permanent). Storage classes decide if a variable is temporary or permanent, and if it can be seen by other parts of the program.
For example, auto variables are like notes you write on a sticky note and throw away after use—they exist only inside a small area (a function). static variables are like notes you keep in a drawer—they stay around even after you close the notebook, but only you can see them. extern variables are like notes shared between friends—they let different parts of the program share information.
Example
This example shows how different storage classes affect variable behavior inside and outside functions.
#include <stdio.h> int global_var = 10; // extern by default void demo() { auto int a = 5; // auto storage class static int b = 0; // static storage class register int c = 15; // register storage class b++; // static keeps its value between calls printf("auto a = %d, static b = %d, register c = %d, global_var = %d\n", a, b, c, global_var); } int main() { demo(); demo(); return 0; }
When to Use
Use storage classes to control how variables behave in your program. Use auto for normal local variables that only need to exist during a function call. Use static when you want a variable to remember its value between function calls but keep it hidden from other parts of the program. Use extern to share variables between different files or parts of your program. Use register to suggest the compiler keep a variable in a CPU register for faster access (though modern compilers often ignore this).
For example, static is useful for counters inside functions, and extern is helpful when you split your program into multiple files but want to share data.
Key Points
- auto: Default for local variables, limited to function scope.
- register: Suggests fast access by CPU registers.
- static: Preserves variable value between calls, limits scope to file or function.
- extern: Declares variables defined elsewhere, allows sharing across files.