Thursday, September 24, 2009

STORAGE CLASSES

The storage class determines the part of member storage is allocated for an object and how long the storage allocation continues to exit.



Storage class tells us:


1) Where the variable is stored.


2) Initial value of the variable.


3) Scope of the variable.Scope specifies the part of the program which a variable is accessed.


4) Life of the variable.


There are four types of storage classes:


1) Automatic storage class


2) Register storage class


3) Static storage class


4) External storage class


AUTOMATIC STORAGE CLASS:


In this automatic storage class,


Variable is stored in memory.


Default value is garbage value


Scope is local to the block


Life is, with in the block in which the variable is defined


Example 1:


main()
{
        auto int i=10;
        printf(“%d”,i);
}


Output:


10


Example 2:


main()
{
       auto int i;
       printf(“%d”,i);
}


Output:


1002


In example 1, i value is initialised to 10.So,output is 10.


In example 2, i value is not initialised.So,compiler reads i value is a garbage value.


REGISTER STORAGE CLASS:


Variable is stored in CPU registers.


Default value is garbage value.


Scope is local to the block.


Life is,with in the block in which the variable is defined.


We can not use register storage class for all types of variables.


For example:


register float f;


register double d;


register long l;


Example :


main()
{
       register int i=10;
       printf(“%d”,i);
}


Output:


10


STATIC STORAGE CLASS:


Variable is stored in memory.


Default value is zero.


Scope is local to the block.


Life is,value of the variable persists between different function calls.


Example :


main()
{
       add();
       add();
}


add()
{
     static int i=10;
     printf(“\n%d”,i);
     i+=1;
}


Output:


10


11


EXTERNAL STORAGE CLASS:


Variable is stored in memory.


Default value is zero.


Scope is local to the block.


Life is,as long as the program execution doesn’t come to an end.


Example :


int i=10;


main()
{
       int i=2;
       printf(“%d”,i);
       display();
}


display()
{
      printf(“\n%d”,i);
}


Output:


2


10


In above example,i declared in two places.One is above the main(),second is within main().Within main() i is used in within main() only.Before main() i is used to outof the main() functions.i.e, display() uses the i value as 10.


NOTE:


Static and auto storage classes both are different in the case of life.Remaining all r same.


In the case of recursive function calls we use static storage class.


Register storage classes are used in the case of frequently used variables.Because these are stored in CPU registers.


Extern storage class for only those variables are used almost all functions in the program.This would avoid unnecessary passing of the variables.

1 comment:

  1. I want detailed explanation regarding memory allocation of all storage classes..........

    ReplyDelete