Classes

Storage classes

  • Each and every variable declared in C contains storage class of a variable.
  • The compiler will assume its storage class as default.
  • Storage class of variable tells us about Storage places of the variable i.e Memory or cpu registers.
  • And also tells us about Initial value , scope life time of the variable.

Types of storage classes in C.

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

Demonstration of auto storage class

void main()
{
auto int i,j=5;
int k, l=10;
printf(“\n value of i and j is %d %d\n”,i,j);
printf(“\n value of k and l is %d %d\n”,k,l);
}

Output: value of i and j is 2009 5
vlaue of k and l is 1005 10

Auto is default storage class, so no need to define it.
The value of i and k are garbage value.

Register storage class

A variable is nothing but a memory location in the main memory of the computer and cpu access them to manipulate the variable. This process slow down the execution of the program as the main memory is 10 times slower than the cpu, so for the fast execution of program we can use cpu register.

Demonstration of Register storage class

void main(){
register int i;
for(i=1; i<=100; i++) printf("\n %d",i); }

Static storage class
If it is required that the value of variable remain same after the execution of the program we use static storage class.
it will lock the variable value .

Demonstration of static storage class

#include
#include
void main()
{
int i, r;
clrscr();
for(i=1; i<=5; i++){ r=total(i); printf("\t %d",r); } getch(); } total(int x) { static int s=0; s=s+x; return(s); }

output : 1 3 5 10 15

value locked in static variable s in first step s=0 , s=0+1 s=1, now in 2nd loop s will not be equal to 0 it will be 1 as it is static .

External storage class
External variable are declared outside all function.

int i;
void main(){
printf(“\n i=%d”,i);
increment();
decrement();
}

increment(){
i++;
printf(“\n i=%d”,i);
}
decrement(){
i–;
printf(“\n i=%d”,i);
}

output:
i=0
i=1
i=0