C - SPLessons

Chapter 11

Storage Classes in C

Storage Classes in C

The Storage Classes in C Language decides

The specifiers which determines storage classes in C are called as Storage Class Specifiers, which are categorized into 4 types.

Automatic Storage Class 

The variables declared inside a block without any storage class specification can be considered as automatic storage class.

  1. These variables are also called as local variables as they get destroyed after the execution of the block.
  2. As the variables are created automatically, garbage values are assigned by the compiler.

Register Storage Class

The variables stored in register storage class are similar to automatic storage classes in C.

  1. Scope of the variable is same as automatic class.
  2. Register variables are stored in CPU registers in order to retrieve the values faster.
  3. Provides space for only few variables as the register size is very low.
  4. The default value is the garbage value(could be anything).


#include<stdio.h>
void main()
{
	register int i = 1;
	int *p = &i; //error : address cannot be retreived.
	printf("Value of i: %d", *p);
	printf("Address of i: %u", p);
}

Extern Storage class

The variables declared with “extern” keyword states that the value possessed by that variable is already in use.

  1. Extern variables are also called as global variables, because if the value is specified in one file, it can be accessed by other files also. No storage space is allotted to these variables.
  2. Default value of any external variable is ‘0’ (zero).

In the below example, the value 75 is declared with a keyword extern which can be used by other functions like display().

#include<stdio.h>
int num =  75 ;  //extern variable

void display();

void main()
{
	 extern int num ;
	 printf("\nNum : %d",num);
	 display();
}

void display()
{
	 extern int num ;
	 printf("\nNum : %d",num);
}

Output:

Enter the Number 1 : 5

Enter the Number 2 : 10

Sum of Numbers : 15

Static Storage class

Static Storage classes in C consists of variables which can retain its value depending on the function call.

  1. The scope of the variable will not be effected i.e. variable remains local to the block in which it lies.

In the below example, irrespective of the scope, the value got incremented depending on the function call.

#include<stdio.h>
void increment();
void main()
{
	increment();
	increment();
	increment();
}
void increment()
{
	static int a = 0;//Static variable
	a = a+1;
	printf("%d\t",a);
}

Output:

1       2       3

Summary

  • Storage class decides scope, visibility and life-time of a variable.
  • auto storage class variables are deleted after execution.
  • register variables stores only some values.
  • extern variables are operated and declared outside the program.
  • static variables value can be changed as per the function call.