Storage Classes in C Language:
Storage Classes in C
Storage classes in C define the scope (visibility) and lifetime of variables and/or functions within a C program. There are four types of storage classes in C:
- auto
- register
- static
- extern
auto Storage Class
The auto
storage class is the default storage class for local variables. It is used to define local variables that are created and initialized when the block is entered, and destroyed when the block is exited.
#include
int main() {
auto int a = 10; // 'auto' is optional
printf("Value of a: %d\n", a);
return 0;
}
register Storage Class
The register
storage class is used to define local variables that should be stored in a register instead of RAM. This makes the variable faster to access. However, it is up to the compiler to decide whether to use a register or not.
#include
int main() {
register int a = 10;
printf("Value of a: %d\n", a);
return 0;
}
static Storage Class
The static
storage class has three distinct uses:
- To preserve the value of a variable inside a function across multiple calls.
- To make a global variable or function visible only to the file in which it is declared.
- To provide internal linkage.
Preserving Variable Value
#include
void demo() {
static int count = 0; // This variable is initialized only once
count++;
printf("Count: %d\n", count);
}
int main() {
demo();
demo();
demo();
return 0;
}
Internal Linkage
static int globalVar = 10; // Visible only within this file
static void demo() {
printf("This function is visible only within this file.\n");
}
extern Storage Class
The extern
storage class is used to declare a global variable or function in another file. The extern
keyword tells the compiler that the variable or function exists, even if its definition is in another file.
// File 1: main.c
#include
extern int count; // Declaration of the variable
int main() {
count = 5;
printf("Count: %d\n", count);
return 0;
}
// File 2: support.c
int count; // Definition of the variable