Storage Classes in C

Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto:
  • extern
  • static
  • register

  • Storage ClassesStorage PlaceDefault ValueScopeLife-time
    autoRAMGarbage ValueLocalWithin function
    externRAMZeroGlobalTill the end of main program, May be declared anywhere in the program
    staticRAMZeroLocalTill the end of main program, Retains value between multiple functions call
    registerRegisterGarbage ValueLocalWithin function
    1) auto

    The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

    #include <stdio.h>  
    void main( ) {  
    int a=20;  
    auto int b=20;   //same like above  
    printf("%d %d",a,b);  
       }  
    Output: 20   20
    
    2) register
    The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.
    register int counter = 0;
    3) static
    The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call. The static variable has the default value 0 which is provided by compiler.
    #include <stdio.h>  
    void change( )  {  
    static int i=0;  //static variable  
    int j=0;    //local variable  
    i++;  
    j++;  
    printf("i =  %d and j =  %d\n", i, j);  
     }  
    void main( )  {  
    change();  
    change();  
     }  
    Output:
    i= 1 and j= 1
    i= 2 and j= 1
    
    4) extern
    The extern variable is visible to all the programs. It is used if two or more files are sharing same variable or function.
    extern int counter=0;