Storage

A storage class identifies the visibility of variables or functions in a C program. There are 4 different storage classes in a C language.

  • static

  • register

  • auto

  • extern

 

Register Storage Class

The register storage class is to define local variables and should be stored in a register instead of RAM. Here is an example syntax of the register storage class.

 

{

   register int  rollNo;

}

 

Static Storage Class

Static storage class tells the compiler to keep local variables for a lifetime. Making local variables static allows them to maintain their values when function call. Here is a C program for static storage class.

 

Program:

#include <stdio.h>

 

/* Declare a function */

void func(void);

 

static int count = 10; /* global variable */

 

main() {

 

   while(count--) {

      func();

   }

 

   return 0;

}

 

/* Define a function */

void func( void ) {

 

   static int i = 5; /* Create local static variable */

   i++;

 

   printf("i is %d and count is %d\n", i, count);

}

 

Output:

i is 12 and count is 3

i is 13 and count is 2

i is 14 and count is 1

i is 15 and count is 0

 

Extern Storage Class

The external storage is generally used to give a reference to the global variables. It is visible for all the program files and cannot be initialized. Also, points the variable name at a storage location. Let's have a look at the short example of extern storage.

 

Program:

1rst File main.c

 

#include <stdio.h>

 

int count ;

extern void w_e();

 

main() {

   count = 5;

   w_e();

}

 

2nd File second.c

#include <stdio.h>

 

extern int count;

 

void w_e(void) {

   printf("Count is %d\n", count);

}

 

Extern storage class is used to declare count in second.c file.

Output:

count is 5