Storage Classes in C
In C programming, a storage class defines the scope, visibility, lifetime, and default value of a
variable.
There are four storage classes in C:
1. Automatic (auto)
2. Register (register)
3. Static (static)
4. External (extern)
1. Auto Storage Class
- The 'auto' keyword is the default storage class for local variables.
- Variables are stored in the main memory (RAM).
- They have block scope and are automatically deallocated when the function exits.
#include <stdio.h>
void test() {
auto int x = 10; // Auto variable
printf("%d", x);
}
int main() {
test();
return 0;
}
2. Register Storage Class
- The 'register' keyword stores the variable in the CPU register instead of RAM.
- It provides faster access.
- Cannot use '&' operator to get the address of register variables.
#include <stdio.h>
int main() {
register int x = 5;
printf("%d", x);
return 0;
}
3. Static Storage Class
- The 'static' keyword retains variable value even after the function exits.
- The variable is initialized only once.
#include <stdio.h>
void counter() {
static int count = 0; // Static variable
count++;
printf("%d ", count);
}
int main() {
counter();
counter();
return 0;
}
4. External Storage Class
- The 'extern' keyword allows a variable to be accessed across multiple files.
- The variable is declared in one file and used in another.
// File 1: extern_var.c
#include <stdio.h>
int num = 10; // Global variable
// File 2: main.c
#include <stdio.h>
extern int num; // Accessing the global variable
int main() {
printf("%d", num);
return 0;
}