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:
auto
static
register
extern
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.
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:
gcc main.c data.c -o program