11 Storage Classes – Programming in C, 3/e, 3rd Edition

CHAPTER 11

Storage Classes

Chapter Outline
11.1  INTRODUCTION

The variables declared in C programs are totally different from other languages. We can use the same variable names in the C program in separate blocks. When we declare a variable, it is available only to a specific part or block of the program. Remaining block or other functions cannot access the variable. Variables declared within function are called internal variables and those declared outside are called external or global variables.

The area or block of the C program from where the variable can be accessed is known as the scope of variables. The area or scope of the variable depends on its storage class, i.e. where and how it is declared. There are four scope variables.

  1. Function
  2. File
  3. Block
  4. Function prototype

The storage class of a variable tells the compiler:

  1. the storage area of a variable
  2. the initial value of a variable if not initialized
  3. the scope of a variable
  4. the life of a variable, i.e. how long the variable would be active in a program.

Any variable declared in C can have any one of the above four storage classes:

  1. Automatic variables
  2. External variables
  3. Static variables
  4. Static external variables
  5. Register variables

The storage class determines storage duration, scope and linkage. The variable’s storage duration is the period during which the variable exists in the memory. Some kind of variables are repeatedly created in memory and some exist throughout the program execution.

Another important aspect is scope, i.e. the area in which the variable can be accessed. Some variables are global and can be accessed anywhere in the program. On the other hand, some variables are of limited scope in the block where they are defined. The above declared four kinds of storage classes can be further divided into two types, depending on the storage duration. They are automatic storage duration and static storage duration. Generally, local variables have automatic storage where the use of keyword auto is optional. Static variables belong to static storage class defined as static and external keywords. From the above discussion,we can state that there are two types of storage classes, i.e. (i) local and (ii) global; and storage class specifiers are auto, register,static and extern.

11.1.1  Lifetime of a Variable

Every variable has its lifetime, i.e. its time duration during which its status is active in the program. We can also say that lifetime of a variable is the time gap between its declaration and cleanup. The life time depends upon the storage class. For example, auto variable gets destroyed immediately when the function execution is over, whereas static variable remains in the memory.

11.1.2  Visibility of a Variable

Visibility of a variable is another property. It defines its scope. The scope is of two types, i.e. local and global. Global is recognized throughout the program, whereas the local variable scope is limited to the declaration block.

11.2  AUTOMATIC VARIABLES

The auto variables are defined inside a function. A variable declared inside the function without storage class name is, by default, an auto variable. These functions are declared on the stack. The stack provides temporary storage. The scope of the variable is local to the block in which they are defined. These variables are available only to the current block or program. Once the executions of the function take place and return turns off the function, the contents and existence of the auto variables or local variables vanish. Whenever a function is executed, all auto variables are allocated memory and de-allocated when the execution of function ends. auto variables are safe, i.e. they cannot be accessed directly by other functions.

The keyword ‘auto’ is used for declaration of automatic variables. By default, every variable pertains to auto storage class.

Some programs are given on auto storage class.

  11.1  Write a program to show the working of the auto variable.

 

void main()

{

auto int v=10;

clrscr();

call2();

printf(“\nV=%d”,v);

}

void call1()

{

auto int v=20;

printf(“\nV=%d”,v);

}

call2()

{

auto int v=30;

call1();

printf(“\nV=%d”,v);

}

OUTPUT:

V=20

V=30

V=10

Explanation:

In the above program, the variable ‘v’ is declared and initialized in three different functions. Each function, when called, prints the local values of variables ‘v’, which are shown at the output. When a function is called,it declares its own variable ‘v’, and when a function terminates, the local variable ‘v’ is destroyed. Here, every function has its own variable ‘v’ with different values. The three variables ‘v’ are having their own unique memory locations. Even after the removal of auto word from the program, there will not be any error thrown by the compiler. The reader can verify this fact.

  11.2  Write a program to show the working of auto variables in different blocks.

 

void main()

{

int x=10;

clrscr();

printf(“\n X=%d”,x);

  {

    int x=20;

    printf(“\n X=%d”,x);

  }

    printf(“\n X=%d”,x);

}

OUTPUT:

X=10

X=20

X=10

Explanation:

In the above program, declaration of ‘x’ is made two times with different values. Before the second block, the value of ‘x’ was 10. The control passes to the second block and again ‘x’ is declared and assigned a new value 20. When the control exits from the second block, the value of second ‘x’ disappears and the value of current block, i.e. 10, is printed. In the second variable, declaration int x=20, i.e. we declared another variable ‘x’ different from the first variable ‘x’. If we declare only x=20, i.e. changing the value of the first ‘x’, no second variable ‘x’ is created. Hence, int tells the compiler to create a new variable and allocates two bytes for it in the memory.

  11.3  Write a program to use the same variable in different blocks with different data types.

 

void main()

{

int x=10;

clrscr();

printf(“\n X=%d”,x);

{

  float x=2.22;

  printf(“\n X=%g”,x);

}

{

  char *x=”Auto Storage Class”;

  printf(“\n X=%s”,x);

}

  printf(“\n X=%d”,x);

}

OUTPUT:

X=10

X=2.22

X=Auto Storage Class

X=10

Explanation:

The above program is the same as the previous one. Here, in each block, the variables are defined with different data types.

11.3  EXTERNAL VARIABLES

The external storage class indicates that the variable has been defined at other place other than the place where it is declared. It can be declared in another source file. The variable declaration generally appears before main() and use of keyword extern is optional. Initialization cannot be done because its value is defined in another source file. Memory is not allotted in the source program, and it is allotted, where it is defined.

The variables that are available to all the functions, i.e. from entire program, can be accessed. The variables are called external or global variables. External variables are declared outside the function body. In case, in a program both external and auto variables are declared with the same name, the first priority is given to the auto variable. In this case, external variable is hidden. If we declare external variables in the program, there is no need to pass these variables to other function. The compiler does not allocate memory for these variables. It is already allocated for it in another module where it is declared as a global variable.

  11.4  Write a program to demonstrate the use of external variables.

 

int j=4;

void main()

{

extern int j;

clrscr();

j=j*3;

printf(“j=%d”,j);

fun();

printf(“\nj=%d”,j);

}

fun ()

{

j=j*j;

}

OUTPUT:

j=12

j=144

Explanation:

In the above program, variable j is declared and initialized with 4. The second declaration inside the main() with keyword external indicates that it is declared already. The expression j = j*3 gives the result 12, i.e. the value of j considered is 4. In the function fun(), the value of j is considered 12, i.e. the last result and hence, the result 144. We can also declare the statement int j=4 in another file. The file must be included in the main program. Consider the program below:

 

FILE v.c

int j=4;

  11.5  Write a program to demonstrate the use of the external variables.

 

# include “v.c”

void main()

{

extern int j;

clrscr();

j=j*3;

printf(“j=%d”,j);

fun();

printf(“\nj=%d”,j);

}

fun()

{

j=j*j;

}

OUTPUT:

j=12

j=144

Explanation:

This program is the same as the last one. Only the statement int j=4 is stored in the file v.c. The file is included in the main program. The output is the same.

  11.6  Write a program to show the working of the external variables.

 

int v=10;

void main()

{

clrscr();

call1();

call2();

printf(“\n In main() V=%d”,v);

}

call1()

{

printf(“\n In Call1() V=%d”,v);

}

call2()

{

printf(“\n In call2() V=%d”,v);

}

OUTPUT:

In Call1() V= 10

In call2() V= 10

In main() V= 10

Explanation:

In the above program, variable ‘v’ is declared outside the function body and initialized to the value 10. Every function can access the variable ‘v’, so no re-declaration or local variable is created. Every function in turn prints the value of ‘v’. The same value is printed by all the functions.

  11.7  Write a program to show the working of auto and global variables with the same name.

 

int v=10;

void main()

{

clrscr();

call1();

call2();

printf(“\n In main() V=%d”,v);

}

call1()

{

int v=20;

printf(“\n In Call1() V=%d”,v);

}

call2()

{

printf(“\nIn call2() V=%d”,v);

}

OUTPUT:

In Call1() V= 20

In call2() V= 10

In main() V= 10

Explanation:

In the above program, an external variable and global variables are declared with the same name. In such a case, when call1() function is called, the local variable ‘v’ of call1() hides the global variable ‘v’. As soon as the control returns back from the call1() function, the local variable ‘v’ will be destroyed and the global variables ‘v’ appear.

  11.8  Write a program to declare external variables using the extern keyword.

 

int m=10;

void main()

{

extern int m;

clrscr();

printf(“\n m=%d”,m);

}

OUTPUT:

m = 10

Explanation:

In the above program, variable ‘m’ is declared and initialized with 10 before the main() function. The variable ‘m’ is again re-defined with extern keyword. The extern keyword is optional.

11.4  STATIC VARIABLES

The static variable may be of an internal or external type, depending where it is declared. If declared outside the function body, it will be static global. In case, declared in the body or block, it will be an auto variable. When a variable is declared as static, its garbage value is removed and initialized to NULL value. The contents stored in these variables remain constant throughout the program execution. A static variable is initialized only once; it is never reinitialized. The value of the static variable persists at each call and the last change made in the value of the static variable remains throughout the program execution. Using this property of the static variable, we can count how many times a function was called.

The following programs illustrate the working of static variables.

  11.9  Write a program to show the use of the static variable.

 

void main()

{

clrscr();

for(;;)

print();

}

print()

{

int static m;

m++; printf(“\nm=%d”,m);

if(m==3)

exit(1);

}

OUTPUT:

m=1

m=2

m=3

Explanation:

In the above program, print() function is called. The variable ‘m’ of print() function is the static variable. It is increased and printed in each call. Its contents persist at every call. In the first call,its value is changed from 0 to 1, in the second call from 1 to 2, and in the third call from 2 to 3.

  11.10  Write a program to show the difference between variables of auto and static class,when they are not initialized.

 

void main()

{

int x;

static int y;

clrscr();

printf(“\nx=%d & y=%d”,x,y);

}

OUTPUT:

x=1026 & y =0

Explanation:

In the above program, variables ‘x’ and ‘y’ are declared as integer variables. The variable ‘y’ is a static variable. Both variables are printed. The value of ‘x’ printed is some garbage, i.e.1026 and ‘y’ is 0. When we declare a variable as static, it is automatically initialized to zero,otherwise some garbage is assigned to its vacant locations.

11.5  STATIC EXTERNAL VARIABLES

The static external variable can be accessed as external variables only in the file in which they are defined. No other file can access the static external variables that are defined in another file.

  11.11  Program to demonstrate the use of static external Variable.

#include <stdio.h>

#include <conio.h>

static int i;

int main()

{

i=20;

clrscr();

printf(“\n The value of I is : %d”,i);

getch();

return 0;

}

OUTPUT:

The value of i is : 20

Explanation:

In the above program, the external variable ‘i’ is accessed within the scope of this program only. Other files cannot access a static external variable that is defined in another file.

Note: The difference between an ordinary external variable and a static external variable is of scope. An ordinary external variable is visible to all functions in the file and can be used by functions in other files. A static external variable is visible only to functions in its own file and below the point of definition.

11.6  REGISTER VARIABLES

We can also keep some variables in the CPU registers instead of memory. The keyword register tells the compiler that the variable list followed by it is kept on the CPU registers, since register access is faster than the memory access. If the CPU fails to keep the variables in CPU registers, in that case, the variables are assumed as auto and stored in memory. CPU registers are limited in number. Hence, we cannot declare more variables with register variables. However, compiler automatically converts register variables to non-register variables, once the limit is reached. User cannot determine the success or failure of register variables. We cannot use register class for all types of variables. The CPU registers 8086 in microcomputer are 16 bit registers. The data types float and double need more than 16 bits space. If we define variables of these data type with register class, no errors will be shown. The compiler treats them as a variable of auto sclass.

Syntax:

 

register int k;

  11.12  Write a program to declare and use variable of register class.

 

void main()

{

register int m=1;

clrscr();

for(;m<=5;m++)

printf(“\t%d”,m);

}

OUTPUT:

1   2   3   4   5

Explanation :

In the above program, variable ‘m’ is declared and initialized to 1. The for loop displays values from 1 to 5. The register class variable is used as a loop variable.

SUMMARY

After studying this chapter, your understanding in regard to the variables is now perfect. You have studied the variables and their motives. The variables are declared using storage class in different blocks and functions. You have also gained the knowledge of auto storage class used to define local variables, static storage class used to initialize variables with null, register storage class to use CPU registers for storage of data and extern storage class to declare global variables. Now, programmer must have gained knowledge on static external variables and their access, in the file in which they are declared. Varied easy examples have been illustrated on the above storage classes. The reader is advised to execute the programs provided in this chapter, in order to understand the concepts and applications of the storage class.

EXERCISES

I  Match the following correct pairs given in Group A with Group B :

  1.  

  2.  

II  Select the appropriate option from the multiple choices given below:

  1. A static variable is one that
    1. retains its value throughout the life of the program
    2. cannot be initialized
    3. is initialized once at the commencement of the execution and cannot be changed at the runtime
    4. is the same as an automatic variable but is placed at the head of the program
  2. An external variable is one
    1. which is globally accessible by all functions
    2. which is declared outside the body of any function
    3. which resides in the memory till the end of the program
    4. all of the above
  3. If a storage class is not mentioned in the declaration then default storage class is
    1. automatic
    2. static
    3. external
    4. register
  4. If the CPU fails to keep the variables in CPU registers,in that case the variables are assumed
    1. automatic
    2. static
    3. external
    4. None of the above
  5. What will be the value of variable ‘x’ on the execution of the following program?

    int x;

    void main()

    {

      clrscr();

      x++;

      printf(“\n %d”,x);

    }

    1. x=1
    2. x=0
    3. garbage value
    4. None of the above

III  Attempt the following programs:

  1. Write a program to calculate the sum of digits of the entered number. Create user-defined function sumd(). Use the static variable and calculate the sum of digits.
  2. Write a program to call function main() recursively. The program should be terminated when the main() function is called during 5th time. Take help of the static variable.
  3. Write a program to calculate the triangular number. Use the static variable with the user-defined function.
  4. Write a program to create the for loop from 1 to10000. Declare the loop variable of class register and auto. Observe the time required for completing the loop for both types of variables. Find out in which class the execution time is minimum.

IV  Answer the following questions:

  1. List and explain the four scope variables in brief.
  2. What are the automatic variables?
  3. Distinguish between static and external variables.
  4. Briefly explain register variables.
  5. List the limitations of register variables.
  6. Why register storage class does not support all data types?
  7. Can we declare a variable in different scopes with different data types? Answer in detail.
  8. Explain lifetime and visibility of a variable.

V  What will be the output/s of the following program/s?

  1. void main()

    {

    int v=5;

    clrscr();

      {

      int v=4;

      printf(“ %d “,v);

      }

      printf(“ %d “,v);

      {

      int v=9;

      printf(“ %d “,v);

      }

    printf(“ %d “,v);

    }

  2. void main()

    {

    int x=11;

    clrscr();

    printf(“\n x=%d”,x);

      {

      float x=2.5;

      printf(“ x=%g”,x);

      }

      {

      char *x=”Auto Storage Class”;

      printf(“ x=%s”,x);

    }

    }

  3. int v=10;

    void main()

    {

    clrscr();

    call1();

    call2();

    printf(“In main()”);

    }

    call1()

    {

    printf(“ Incall1()”);

    }

    call2()

    {

    printf(“ In call2()”);

    }

  4. int v=10;

    void main()

    {

    clrscr();

    call1();

    call2();

    printf (“ In main()”);

    }

    call1()

    {

    printf(“ In call1() v=%d”,v);

    }

    call2()

    {

    printf(“ In call2()

    v=%d”,v);

    }

  5. int v=10;

    void main()

    {

    clrscr();

    for(;;)

    print();

    }

    print()

    {

    int static m;

    m++;

    printf(“ %d”,m);

    if (m==3) exit(0);

    }

  6. void main()

    {

    auto int j=2;

    clrscr();

    {

      {

        {

        printf(“%d”,j);

      }

      printf(“ %d”,j);

      }

      printf(“ %d”,j);

    }

    }

  7. void main()

    {

    auto int j=1;

    clrscr();

    {

      auto int j=2;

      {

        auto int j=3;

        printf (“%d”,j);

      }

      printf(“%d”,j);

    }

    printf(“%d”,j);

    }

  8. void main()

    {

    clrscr();

    increment();

    increment();

    increment();

    }

    increment()

    {

    static int j=1;

    printf(“\n%d”,j);

    j++;

    }

VI  Find the bug/s in the following program/s:

  1. Auto int x=20;

    void main()

    {

    auto int x=10;

    clrscr();

    printf(“\nx=%d”,x);

    }

  2. void main()

    {

    register x=10;

    printf(“\nx=%d”,x);

    }

  3. void main()

    {

    clrscr();

    value();

    }

    static value()

    {

    printf(“Hi”);

    }

  4. void main()

    {

    int x=25;

    clrscr();

    printf(“%d\n”,x);

    show();

    }

    show()

    {

    printf(“%d”,x);

    }

  5. void main()

    {

    int count =5;

    printf(“\n%d”,count--);

    if (count!=0) main();

    }

  6. float x=5.5;

    void main()

    {

    float y,f();

    clrscr();

    x*=4.0;

    y=f(x);

    printf(“%g %g”,x,y);

    }

    float f(float a)

    {

    a+=1.3;

    x-=4.5; return a+x;

    return 0;

    }

  7. register int i;

    void main()

    {

    clrscr();

    for(i=3;i>0;i--)

    printf (“\ % d”,i);

    getche();

    }

ANSWERS

I  Match the following correct pairs given in Group A with Group B:

  1.  

    Q.

    Ans.

    1.

    A

    2.

    E

    3.

    B

    4.

    C

    5.

    D
  2.  

    Q.

    Ans.

    1.

    B

    2.

    D

    3.

    C

    4.

    A

II  Select the appropriate option from the multiple choices given below:

Q.

Ans.

1.

a

2.

d

3.

a

4.

a

5.

a

V  What will be the output/s of the following program/s?

Q.

Ans.

1.

4  5  9  5

2.

x=11 x=2.5 x=Auto Storage Class

3.

In call1() In call2()In main()

4.

In call1() v=10 In call2() v=10 In main()

5.

1  2  3

6.

2  2  2

7.

321

8.

1

 

2

 

3

VI  Find the bug/s in the following program/s:

Q.

Ans.

1.

Automatic variables cannot be defined outside functions.

2.

No Bug.

3.

No Bug.

4.

variable x should be defined.

5.

count should be static.

6.

return 0 should be removed and function declaration should be f(float) in third line.

7.

Incompatible storage class.