Tuesday, November 1, 2011

Automatic Storage Class in C programming language

The features of a variable defined to have an automatic storage class are as under:
Storage
− Memory.
Default initial value
− An unpredictable value, which is often called a garbage value.
Scope
− Local to the block in which the variable is defined.
Life
− Till the control remains within the block in which the variable is defined.
Following program shows how an automatic storage class variable is declared, and the fact that if the variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
The output of the above program could be...
1211 221
where, 1211 and 221 are garbage values of i and j. When you run this program you may get different values, since garbage valuesare unpredictable. So always make it a point that you initialize the automatic variables properly, otherwise you are likely to get unexpected results. Note that the keyword for this storage class is auto, and not automatic.
Scope and life of an automatic variable is illustrated in the following program.
main( )
{
auto int i = 1 ;
{
{
{
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
}
The output of the above program is:
1 1 1
This is because, all printf( ) statements occur within the outermost block (a block is all statements enclosed within a pair of braces) in which i has been defined. It means the scope of i is local to the block in which it is defined. The moment the control comes out of the block in which the variable is defined, the variable and its value is irretrievably lost. To catch my point, go through the following program.
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "\n%d ", i ) ;
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
The output of the above program would be:
3 2 1

Note that the Compiler treats the three i’s as totally different variables, since they are defined in different blocks. Once the control comes out of the innermost block the variable i with value 3 is lost, and hence the i in the second printf( ) refers to i with value 2. Similarly, when the control comes out of the next innermost block, the third printf( ) refers to the i with value 1.
Understand the concept of life and scope of an automatic storage class variable thoroughly before proceeding with the next storage class.

No comments:

Post a Comment