NIOS Computer Science: Chapter 12 – Function Part 7

Download PDF of This Page (Size: 354K)

Figure shows types of Storage Classes

Figure Shows Types of Storage Classes

Figure shows types of Storage Classes

i. Automatic variable

All variables by default are auto, i.e., the declarations int a and auto int an area equivalent.

Auto variables retain their scope till the end of the function in which they are defined.

An automatic variable is not created until the function in which it is defined is called.

When the function exits and control is returned to the calling program, the variables are destroyed and their values are lost.

The name automatic is used because the variables are automatically created when a function is called and automatically destroyed when it returns.

Example 5

# include<iostream.h>

void sum (int);

void main ( )

{

int i;

for (i = 1; i < =5; i + +)

sum (i);

}

void sum (int n)

{

auto int s = 0;

s = s + n;

cout << s << “\n”;

}

The output of the program is

1

2

3

4

5

ii. Register variable

A register declaration is an auto declaration. A register variable has all the characteristics of an auto variable. The difference is that register variable provides fast access as they are stored inside CPU registers rather than in memory. The register and auto can be applied to local variable.

iii. Static variable

The variable may be static automatic variable or static external variable. The later one is meaningful only in multifile programs.

A static automatic variable has the visibility of a local variable but the lifetime of an external variable.

Thus it is visible only inside the function in which it is defined, but it remains in existence for the life of the program. If in the previous program auto int s = 0 is changed to static int s = 0. The output of the program will be

1

3

6

10

15

iv. External variable

A large program may be written by a number of persons in different files.

A variable declared global in one file will not be available to a function in another file.

Such a variable, if required by functions in both the files, should be declared global in one file and at the same time declared external in the second file.

Example: extern int a;

Where extern is the keyword for external.