i2tutorials

Storage Classes

Storage Classes

 

Commonly we are declaring variables with their data types. To fully define a variable it needs to mention its storage class along with its data type. Variables have a data type and storage class.

A variable in C can be one of the four storage classes:

  1. Automatic storage class
  2. Register storage class
  3. Static storage class
  4. External storage class

The general format of a variable statement that uses the storage class is:

 

 

1. Automatic Storage Class:

 

Features of automatic storage class are as follows:

Storage: Memory

Default Initial Value: Garbage value

Scope: Local to the block where the variable has been defined.

Life: Till the control remains within the block.

 

Example:

 

#include<stdio.h>
main()
{
void function1();
void function2();
int m=1000;
function2();
printf("%d\n",m);
}
void function1()
{
int m=10;
printf("%d\n",m);
}
void function2()
{
int m=100;
function1();
printf("%d\n",m);
}

 

Output:

 

Storage Classes

 

 2. Register Storage Class:

 

Features of register storage class are as follows:

Storage: CPU Registers

Default Initial Value: Garbage value

Scope: Local to the block where the variable has been defined.

Life: Till the control remains within the block.

 

Example:

 

#include <stdio.h>
main()
{
 register int k;
 for(k=1;k<=10;k++)
 printf("%d\n",k);
}

 

Output:

 

 

 3. Static Storage Class:

 

Features of static storage class are as follows:

Storage: Memory

Default Initial Value: Zero

Scope: Local to the block where the variable has been defined.

Life: Value changes between different function calls.

 

Example:

 

#include <stdio.h>
main()
{
void stat();
int i;
for(i=1;i<=3;i++)
 stat();
}
void stat()
{
static int x=0;
x=x+1;
printf("x=%d\n",x);
}

 

Output:

 

 

4. External Storage Class:

 

Features of extern storage class are as follows:

Storage: Memory

Default Initial Value: Zero

Scope: Global

Life: Till the control remains within the program.

 

Example:

 

Source code: prg1.c
#includ<stdio.h>
#include”prg2.c”
int y; // by default global variable acts under extern storage class
main()
{
extern int x;
extern int add(int,int);
printf(“x=%d y=%d”,x,y);
printf(“Sum is %d\n”,add(x,y));
}
Source code: prg2.c
int x=10, y=20;
int add(int a,int b)
{
return a+b;
}

 

OUTPUT:

 

x=10 y=20
Sum is 30

 

Steps to execute extern storage program:

 

  1. Compile the external program prg2.c without any errors.
  2. Compile and execute internal program prg1.c, such that prg1.c links prg2.c during runtime of the program.

 

Exit mobile version