|
extern Storage Type
Apart from auto and static types, a
variable can also be declared in a
manner such that it is available to
all functions in a program file, which
means it is a global variable. A
variable declared outside a function
is called a global variable.
An example of this type of data is
given below:
//Program 8.4
//global variable usage
#include<iostream.h>
int iVal;
void disp(void)
{
cout<<"Value entered is "<<iVal<<endl;
}
void main(void)
{
cout<<"Enter value: ";
cin>>iVal;
disp();
}
Since the variable iVal has been
declared at the begining of the
program, it can be accessed by any
function. The sample output of Program
8.4 would be:
Enter value: 10
Value entered is 10
The extern type data does not allocate
any memory for a variable but merely
declares it to have been created
elsewhere in the program. This
declaration must be used to access a
global variable declared in another
program file. It must also be used to
access a global variable declared
later in the same program file. The
following program illustrates the
usage of global variables and extern
type data:
//Pragram 8.5
//Program to illustrate extern type
data
#include<iostream.h>
int iVal;
void main(void)
{
cout<<"Enter value: ";
cin>>iVal;
disp();
}
//Program 8.6
//The disp funtion
void disp()
{
extern int iVal; //extern is used to
refer to iVal declared in Program 8.5
cout<<"Value entered is "<<iVal;
}
In the above example, Program 8.5
declares a global variable called iVal
and also accepts a value from the
user. Then, it calls a function disp()
which is written in another program
file, namely Program 8.6 . Progarm 8.6
refers to the variable iVal using the
extern declaration since iVal is
declared in Program 8.5 and not in
Program 8.6. Program 8.6 should
contain a #include statement with the
name of the file of Program 8.5. The
sample out put after the two programs
are compiled together and linked would
be:
Enter Value: 10
Value entered is: 10
Summary of the three Storage Types:
|
Storage Type |
Created |
Initialized |
Can be
accessed |
|
auto |
Each
time the function is invoked. |
At the
time of declaration or, later. |
Only
in the function in which it is
declared. |
|
static |
The
first time the function is
invoked |
At the
time of declaration so that the
value is not reset. |
Only
in the function in which it is
declared. |
|
extern |
At the
time when declared as global,
but where declared extern. |
At the
time of declaration or later. |
In any
function in the same/different
program file. |
| |
|
Table
8.1 Scope of Variables of
Different Storage Types |
|