153 views
C Storage Classes
The storage classes are used to define the scope, lifetime, and accessibility of variables. They determine where and when a variable is created, how long it exists, and who can access it. C provides several storage classes, each serving a different purpose. Here are the main storage classes in C:
Automatic Storage Class (auto):
- Variables declared with the
auto
storage class are local to the block in which they are declared. - They are created when the block is entered and destroyed when the block is exited.
- The
auto
keyword is rarely used explicitly because local variables are automatically consideredauto
. For example:
C
int main() {
auto int x; // 'auto' is optional; 'x' is an automatic variable
return 0;
}
Register Storage Class (register):
- Variables declared with the
register
storage class are also local to the block in which they are declared. - They are stored in CPU registers for faster access, but the compiler may ignore this keyword since modern compilers are efficient in optimizing register allocation.
- The
register
keyword is rarely used explicitly. For example:
C
int main() {
register int x; // 'register' is optional; 'x' is a register variable
return 0;
}
Static Storage Class (static):
- Variables declared with the
static
storage class have a lifetime that extends over the entire program. - They are initialized once and retain their values across function calls.
- When used within a function, they are local to the function but persist between function calls.
- When used at the global level (outside any function), they are global and accessible from any part of the program.
C
#include <stdio.h>
void example() {
static int count = 0; // 'count' is a static variable
count++;
printf("Count: %d\n", count);
}
int main() {
example(); // Calls 'example' function
example(); // Calls 'example' function again
return 0;
}
External Storage Class (extern):
- Variables declared with the
extern
storage class are global variables that are defined in another source file. - They are used when you want to access variables defined in other source files.
- The
extern
keyword is used in declarations, not definitions.
C
// In one source file (file1.c)
int globalVar = 42; // Definition of the global variable
// In another source file (file2.c)
extern int globalVar; // Declaration of the global variable from file1.c
Thread Storage Class (_Thread_local):
- This storage class is used to declare thread-local variables in multithreaded programs. Each thread has its own copy of the variable.
- It’s supported in C11 and later versions.
C
#include <stdio.h>
_Thread_local int threadVar = 42;
int main() {
printf("ThreadVar: %d\n", threadVar);
return 0;
}
These storage classes provide control over variable lifetime, scope, and accessibility in C programs. Choosing the appropriate storage class for a variable depends on its intended use and requirements within the program.