Storage Classes

Storage classes in C are used to determine the visibility, lifetime, memory location and initial value of a variable. Type refers to the data type of a variable. There are four types of storage classes in C.

  • Automatic
  • External
  • Static
  • Register
Storage Classes Storage Place Default value ScopeLifetime
auto RAMGarbage ValueLocalWithin function
externRAMZeroGlobalTill the end of the main program maybe declared anywhere in the program.
static RAMZeroLocalTill the end of the main program, retains value between multiple functions call.
registerRegisterGarbage valueLocalWithin the function

Automatic

  • Auto is the default storage class for all the variables and its declared inside a function or a block.
  • Automatic variables are initialized to garbage by default.
  • Memory assigned to automatic variables get free upon exiting from the block.
  • The keyword used for defining automatic variables is auto.
  • In C language auto keyword is rarely used in programs.

Let’s see the example

#include <stdio.h>  
int main()  
{  
int a = 10,i;   
printf("%d ",++a);  
{  
int a = 20;   
for (i=0;i<3;i++)  
{  
printf("%d ",a);  
}  
}  
printf("%d ",a);    
}

Output

11 20 20 20 11

External

  • External storage class variable is defined elsewhere and not within the same block.
  • The default initial value of external integral type is 0 otherwise null.
  • External variable can be declared many times but initialized at once.
  • External variable are initialize globally and we cannot initialize external variable within any block or method.
  • The keyword of external variable is extern.

Let’s see the example of external

#include <stdio.h>  
int a;   
int main()  
{  
extern int a;  
printf("%d",a);  
}

Output

0

Static

  • Static variable are visible only to the functions or to the block in which they are defined.
  • static variable is default initial value is 0 otherwise null.
  • As same static variable can be declared at many times but can be assigned at only once.
  • The keyword used to define static variable is static.

Let’s see the example of static

#include<stdio.h>  
void sum()  
{  
static int a = 10;  
static int b = 24;   
printf("%d %d \n",a,b);  
a++;   
b++;  
}  
void main()  
{  
int i;  
for(i = 0; i< 3; i++)  
{  
sum();     
}

Output

10 24 
11 25 
12 26

Register

  • The access time of the register variable is faster than automatic variable.
  • The initial default value of the register variable is 0.
  • We can store pointers into the register and register can store the address of a variable.
  • Storage class declares register variables which have the same functionality that of the auto variable.

Let’s see the example of register

#include <stdio.h>  
int main()  
{  
register int a;    
printf("%d",a);  
}

Output

0

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews