Storage Classes in C
What is Storage Classes?
It is use to represent visibility and location of a variable.
What does storage classes describe?
1. Variable Scope
2. Variable Location
3. Initial value of variable /Default of variable
4. Lifetime of variable
5. Who can access variable
Types of storage classes:
A. Auto Storage Class
1. It is default variable declaration class; all variables declare without or with auto keyword comes under this category.
2. Its default value is garbage if declare with in a function or zero if declare globally outside of the function.
Example:
int num; = auto int num; //declaration or definition
Program to understand it:
#include<stdio.h>
int num1;
int main(int argc, char const *argv[])
{
auto int num;
printf(“%d”,num); //it will display garbage value
printf(“\n%d”,num1); it will display zero value
return 0;
}
B. Extern Storage Class
1. It is use to access variable from other file
2. Its default value is zero,
3. Its scope is global or can be access outside of program.
Example:
extern int a; //declaration and accessing variable a from other file
extern int b=9; //declaration and definition with a same file as constant value
Program to understand it
Other file: otherfile.c //may be any name
int a=10; //declaration and definition of variable.
int b=30; //same declaration and definition for variable.
Main file: externex.c //may be any file name
#include<stdio.h>
extern int a; //declare only not define
extern int b; //declare only not define
int main(int argc, char const *argv[])
{
printf(“\nValue of A=%d”,a);
printf(“\nValue of B=%d”,b);
return 0;
}
C. Static Storage Class
1. It is use to create such type of variable that value persist even if function remove from memory.
2. Its default value is zero
3. Its scope is global to program, but cannot be access outside of program as extern variable
Example:
static int num;
Program to understand it:
Other file: otherfile.c //may be any name
int counter()
{
static int count=0;
count++;
return count;
}
Main file: staticex.c //may be any name
#include<stdio.h>
int counter1()
{
static int c=0;
c++;
return c;
}
int main(int argc, char const *argv[])
{
printf(“\nValue of Count=%d”,counter());
printf(“\nValue of Count=%d”,counter());
printf(“\nValue of Count=%d”,counter1());
printf(“\nValue of Count=%d”,counter1());
return 0;
}
D. Register Storage Class
1. It is use to create variable that take space in register memory if permitted by compiler.
2. Its default value is garbage.
Example:
register int num;
Program to understand it:
#include<stdio.h>
int main(int argc, char const *argv[])
{
register int b;
printf(“\n%d”,b); //It will print garbage value
return 0;
}