
When you declare a variable in C programming, you may additionally specify the variable’s lifetime or storage specification. In other words, the storage classes of variables in C specify the scope of variables, memory allocation and default value.
Variable Lifetime: The variable’s lifetime indicates how long it will be active during execution. If you define a variable inside a function, the value of the variable will be preserved until the function is run.
How many storage classes in C? In the C program, we have four separate storage classes.
- auto
- extern
- static
- register
Also Read: Basic of C Programming
Table of Contents
auto storage classes in c
The auto storage class in c is the default type of storage. When you use auto to declare a variable, its visibility is confined to the block or function in which it is declared.
When you declare a variable using auto, memory allocation is done for the variable when the function is called, and memory de-allocation id done after the function has completed its execution.
Because every local variable in C is auto by default if you don’t use the auto keyword, variable will be auto variable.
#include <stdio.h>
int main() {
int intVar;
char charVar;
float floatVar;
printf("Int Value: %d\nChar Value: %c\nFloat Value: %f",intVar, charVar, floatVar);
return 0;
}
Output: Int Value: 0 Char Value: Float Value: 0.000000
Fast access is achieved by allocating registers, which is often done for loop counts. A global register variable cannot be declared.
extern storage classes in c
When we need to refer to a function or variable that we have defined elsewhere or will implement later, we use extern storage class.
An extern variable is just like a global variable.
#include<stdio.h>
int a = 15;
int main() {
extern int b;
printf("The value of a is %d", a);
printf("\nThe value of b is %d", b);
return 0;
}
int b = 20;
Output: The value of a is 15 The value of b is 20
register storage classes in c
When you use register to declare a variable, that value of variable is saved in a register. If you need to access a variable several times and need it to be quick, register is the best way to go.
The time it takes to access a register is substantially shorter than it takes to reach main memory.
Because the CPU has a limited amount of registers, the allocation of variables to the registers cannot be guaranteed.
Example: A loop counter, such variable should be stored in register storage class.
#include <stdio.h>
int main() {
register int i = 0;
for (i = 0; i < 5; i++) {
printf("Value of i is %d\n", i);
}
return 0;
}
Output: Value of i is 0 Value of i is 1 Value of i is 2 Value of i is 3 Value of i is 4
static storage classes in c
The value of a static variable persists until the end of the program if it is declared with a static.
#include<stdio.h>
void showValue();
int main() {
showValue();
showValue();
showValue();
return 0;
}
void showValue() {
static int x = 10;
printf("%d ", x);
x = x + 10;
}
Output: 10 20 30