C Storage Classes
C Storage Classes
Storage classes define the lifetime, visibility, and memory location of variables.
There are four main storage class specifiers in C:
autostaticregisterextern
Difference Between Scope and Storage Classes
Scope defines where a variable can be used, and storage classes define how long it lasts and where it's stored. This chapter continues from the C Scope chapter.
auto
The auto keyword is used for local variables. It is the default for variables declared inside functions, so it's rarely used explicitly.
Example
int main() {
auto int x = 50; // Same as just: int x = 50;
printf("%d\n", x);
return 0;
}
static
The static keyword changes how a variable or function behaves in terms of lifetime and visibility:
- Static local variables keep their value between function calls.
- Static global variables/functions are not visible outside their file.
Example
void count() {
static int myNum = 0; // Keeps its value between calls
myNum++;
printf("num = %d\n", myNum);
}
int main() {
count();
count();
count();
return 0;
}
Result:
num = 1
num = 2
num = 3
Try to remove the static keyword from the example to see the difference. Without static, myNum is created again with the value 0 every time count() is called, so the program prints num = 1 three times.
register
The register keyword suggests that the variable should be stored in a CPU register (for faster access).
You cannot take the address of a register variable using &.
Note: The register keyword is mostly obsolete - modern compilers automatically choose the best variables to keep in registers, so you usually don't need to use it.
Example
int main() {
register int counter = 0;
printf("Counter: %d\n", counter);
return 0;
}
extern
The extern keyword tells the compiler that a variable or function is defined in another file.
It is commonly used when working with multiple source files.
File 1: main.c
#include <stdio.h>
extern int shared; // Declared here, defined in another file
int main() {
printf("shared = %d\n", shared);
return 0;
}
File 2: data.c
int shared = 50; // Definition of the variable
Compile both files together, like in the Organize Code chapter:
gcc main.c data.c -o program
The program prints shared = 50, because main.c uses the variable that is defined in data.c.
Tip: In larger programs, the extern line is usually placed in a header file (like data.h), so every file that includes it can use the variable.
Summary
This table shows how long each kind of variable lasts (its lifetime), and where it can be used:
| Keyword | Lifetime | Can be used in |
|---|---|---|
| auto | Until the block ends | The block where it is declared |
| static (local) | The whole program | The block where it is declared |
| static (global) | The whole program | Only its own file |
| register (rarely used today) | Until the block ends | The block where it is declared |
| extern | The whole program | Every file that declares it with extern |