Storage Classes in C

Course- 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 Classes Storage Place Default Value Scope Life-time
auto RAM Garbage Value Local Within function
extern RAM Zero Global Till the end of main program, May be declared anywhere in the program
static RAM Zero Local Till the end of main program, Retains value between multiple functions call
register Register Garbage Value Local Within 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.

 
  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

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.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

 
  1. 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.

 
  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

 
  1. extern int counter=0;