Storage Classes in C Language
0 347
Storage classes in C determine how and where variables are stored in memory and how long they will remain accessible during program execution.
These are divided into Four Types.
1Automatic
2Static
3External
4Register
Storage Classes | Memory storage categories | Standard value | Scope | Lifespan |
auto | Stack | Garbage value | Local | End of Scope |
static | Data memory | Zero | Local | End of Program |
extern | Data memory | Zero | Global | End of Program |
register | CPU Register | Garbage value | Local | End of Scope |
Automatic(auto)
The variable is automatically created and destroyed when you declare variable as a auto in C.
It is a default variable. you don't have to worry about creating and destroying yourself.
Example:
#include<stdio.h>Output:
void function(){
auto int N = 10;
printf("The value of N is %d\n", N);
}
int main(){
function();
return 0;
}
The value of N is 10
Static
When variable is declared as static in C, it means that the variable preserve its value between function call.
Unlike regular variables that are created and destroyed each time a function is called.
static variables keep their function calls within same program.
Example:
#include<stdio.h>Output:
void Afunction() {
static int A =0;
A++;
printf("Function is called %d times\n", A);
}
int main(){
Afunction();
Afunction();
Afunction();
return 0;
}
function is called 1 times
function is called 2 times
function is called 3 times
External
When variable is declared as external in C, that means variable can be accessed across multiple files.
It has global scope, allowing it to be used in functions defined in other file.
Example:
#include<stdio.h>Output:
extern int globalvar = 10;
int main()
{
printf("The value of globalvar is %d\n", globalvar);
return 0;
}
The value of globalvar is 10
Register
When you declare variable in C, you are suggesting to the compiler to store that variable in a CPU register rather than in memory.
CPU registers are tiny storage areas within the processor itself, making access to these variable faster.
However, the compiler may ignore this suggestions to store the variable in CPU register if it is not benefited or need to doing so.
Example:
#include<stdio.h>Output:
int main(){
register int A =10;
printf("value of A is %d\n", A);
return 0;
}
value of A is 10
Share:
Comments
Waiting for your comments