Tuesday, November 1, 2011

External Storage Class data type in C programming language

The features of a variable whose storage class has been defined as external are as follows:
Storage
− Memory.
Default initial value
− Zero.
Scope
− Global.
Life
− As long as the program’s execution doesn’t come to an end.External variables differ from those we have already discussed in that their scope is global, not local. External variables are declared outside all functions, yet are available to all functions that care to use them. Here is an example to illustrate this fact.
int i ;
main( )
{
printf ( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
}
increment( )
{
i = i + 1 ;
printf ( "\non incrementing i = %d", i ) ;
}
decrement( )
{
i = i - 1 ;
printf ( "\non decrementing i = %d", i ) ;
}
The output would be:
i = 0
on incrementing i = 1
on incrementing i = 2
on decrementing i = 1
on decrementing i = 0
As is obvious from the above output, the value of i is available to the functions increment( ) and decrement( ) since i has been declared outside all functions.
Look at the following program.
int x = 21 ;
main( )
{
extern int y ;
printf ( "\n%d %d", x, y ) ;
}
int y = 31 ;
Here, x and y both are global variables. Since both of them have been defined outside all the functions both enjoy external storage class. Note the difference between the following:
extern int y ;
int y = 31 ;
Here the first statement is a declaration, whereas the second is the definition. When we declare a variable no space is reserved for it, whereas, when we define it space gets reserved for it in memory. We had to declare y since it is being used in printf( ) before it’s definition is encountered. There was no need to declare x since its definition is done before its usage. Also remember that a variable can be declared several times but can be defined only once.
Another small issue—what will be the output of the following program?
int x = 10 ;
main( )
{
int x = 20 ;
printf ( "\n%d", x ) ;
display( ) ;
}
display( )
{
printf ( "\n%d", x ) ;
}
Here x is defined at two places, once outside main( ) and once inside it. When the control reaches the printf() in main( ) which x gets printed? Whenever such a conflict arises, it’s the local variable that gets preference over the global variable. Hence the printf( ) outputs 20. When display( ) is called and control reaches the printf( ) there is no such conflict. Hence this time the value of the global x, i.e. 10 gets printed.
One last thing—a static variable can also be declared outside all the functions. For all practical purposes it will be treated as an extern variable. However, the scope of this variable is limited to the same file in which it is declared. This means that the variable would not be available to any function that is defined in a file other than the file in which the variable is defined

No comments:

Post a Comment