There are four storage class in c
  • Automatic
  • Register
  • static
  • extern ( external storage class)

In c programing variables are a fixed number of locations reserved for a specific name. for example below statement
int a;
a is variable name of type integer. assignment of a value will be like a=5; this shows that the name a is of integer type and the name of the location is a. compiler allocates 5 to the location of a. The storage of variable will be either in memory or in cpu register and storage class determines the space according to its storage class. storage class also specify the scope and  initial value of a variable.

Automatic

Automatic variables are local variables whose lifetime ends when execution leaves their scope i.e the value of automatic variable persists only into its scope. Take an example.

#include<stdio.h>
void func()
{
  int a=5;
}
int main()
{
 func();
    printf("%d",a);
return 0;
}

When we compile the above program we will get an error ” error: ‘a’ undeclared (first use in this function)”. this means that variable declared inside a function block is only accessible inside function. also the initial value of automatic variable is a garbage value.

void foo() {
    int i;
    i = 1; // OK: in scope
}
void foom() {
    i = 3; // Error: not in scope
}

Register

register is keyword in c and when we declare a variable like register int i=8 it instruct compiler to store the value of i into cpu register. register access is faster than memory access. register is an storage class in c hence compiler doesn’t allow multiple storage class. as for example below statement will give a compiler error.
register static int b = 8;
Note: b is stored in a register, if possible.

static

global variables or static are automatically initialized with zero in C.For example static 
int a; //although we do not initialize it, the value of a is 0. static declaration also inform the compiler to persist
the updated value of static variable.

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

The output will be 1 2. here if remove static keyword then the variable a has local scope and it will be recreated
each time when execution of program enters into function foo and we will get output: 1 1.

extern storage class and global variable

A variable declared outside of a function is called global variable. The life of global variable remain avaible till the execution of the program.

#include<stdio.h>

int a;
void foo()
{
   a =  1;
}
void foo_2()
{
   a = 2;
}
int main()
{
    return 0;
}

Here global variable a is available in function foo and foo_2.

extern keyword is used in c before an variable declaration like
extern int a;
Here extern inform the compiler that this variable is declared in some other source file.

sa_1416065460extern



Related Contents to follow