Wednesday, April 11, 2012

Storage classes in C

The C programming language supports  a feature called storage class which defines the scope or visibility, life time and memory location of the variable/functions. There are four types of storage classes in C namely
Lets see what is scope and life time of the variables.

Scope or Visibility: Scope means accessibility of the variable. i.e till which part of the code, we can access the variable. for example, if you declare  the variable with in the braces, scope is limited to that block only. Generally variables scope is limited to within the function only. See the sample code below.
main()
{
    int a;
    {
        int b;
        {
            int c;

        }//scope of the variable 'c' ends here

     // cant access variable 'c'

    }//scope of variable 'b' ends here
}

There are four types of scopes in C which are given below.

Block scope: scope of the variable is limited to block. we cant access that variable outside the block. Block of the code is area between the two curly braces as shown in the above sample code.
Function Scope: Scope of the variable is limited to the function. This is the default scope for all the local variables.
File scope: Scope of the variable limited to file. We cant access the variable outside the file. We can limit the variable scope to the file using static storage class.
Application scope: Application scope or program scope of the variable is visible to whole application. This will be implemented by using extern storage class.

Life time of the variable: Life time of the variable is to check whether variable available  in the memory or not. If available , till which portion of the code,  variable is available in the memory without destroying. Even though scope is limited to the block or fucntion , lifetime of that varible available until it destroys in the memory. For each varaible until it is available in the memory, it is having the scope or visibilty. If variable is not available in the memory,  there wont be any scope for that variable.
void lifetime_variable()
{
    // x scope is within this function and life time is whole program becaus of static
    static int x=0; 
    x++;
    printf("x value is %d\n",x);

}
main()
{
   lifetime_variable();
   lifetime_variable();
   lifetime_variable();
}

Output:
x value is 1
x value is 2
x value is 3

In the above sample code, in the function lifetime_variable() variable x  scope is limited to that function only. But life time is through out the program. It wont destroys until program detroys. 

No comments:

Popular Posts