l3 - Storage Classes
l3 - Storage Classes
Storage class in c language is a specifier which tells the compiler where and how to store
variables, its initial value and scope of the variables in a program. Or attributes of variable is
known as storage class or in compiler point of view a variable identify some physical location
within a computer where its string of bits value can be stored is known as storage class.
The kind of location in the computer, where value can be stored is either in the memory or
in the register. There are various storage class which determined, in which of the two
location value would be stored.
There are four types of storage classes and all are keywords:-
1 ) Automatic (auto)
2 ) Register (register)
3) Static (static)
4 ) External (extern)
Examples:-
extern int x;
register char c;
static int y;
Scope of the variable:-what would be the value of the variable of the program.
Life time :- It is the time between the creation and distribution of a variable or how long would
variable exists
features:-
Storage-memory location
Default initial value:-unpredictable value or garbage value.
Life time:-Till the control remains within function or block in which it is defined. It
terminates when function is released.
The variable without any storage class specifier is called automatic variable. Example:-
main( )
auto int i;
printf(“i=”,i);
The keyword used to declare this storage class is register. The features
are:-
Storage:-CPU register.
Life time :-till controls remains within function or blocks in which it is defined.
Register variable don’t have memory address so we can’t apply address operator on it. CPU
register generally of 16 bits or 2 bytes. So we can apply storage classes only for integers,
characters, pointer type.
Variable stored in register storage class always access faster than,which is always stored in the
memory. But to store all variable in the CPU register is not possible because of limitation of
the register pair.
And when variable is used at many places like loop counter, then it is better to declare it as
register class.
Example:-
main( )
register int i;
for(i=1;i<=12;i++)
printf(“%d”,i);
}
The keyword used to declare static storage class is static. Its feature
are:-
Storage:-memory location
Life time:- value of the variable persist or remain between different function call. Example:-
main( )
reduce( );
reduce( );
reduce ( );
reduce( )
printf(“%d”,x);
x++;
Output:-10,11,12
Features are:-
Scope :- global
Example:-
int i,j;
void main( )
{
printf( “i=%d”,i );
receive( );
receive ( );
reduce( );
reduce( );
}
receive( )
{
i=i+2;
printf(“on increase i=%d”,i);
}
reduce( )
{
i=i-1;
printf(“on reduce i=%d”,i);
}
Output:-i=0,2,4,3,2.
When there is large program i.e divided into several files, then external variable should be
preferred. External variable extend the scope of variable.