External (Global) Variables

Global variables are not confined to a single function. Their scope ranges from the point of declaration to the entire remaining program. Therefore, their scope may be the entire program or two or more functions depending upon where they are declared.

Points to remember:

• These are global and can be accessed by any function within its scope. Therefore value may be assigned in one and can be written in another.
• There is a difference in external variable definition and declaration.
• External Definition is the same as any variable declaration:
• Usually lies outside or before the function accessing it.
• It allocates storage space required.
• Initial values can be assigned.
• The external specifier is not required in the external variable definition.
• A declaration is required if the external variable definition comes after the function definition.
• A declaration begins with an external specifier.
• Only when an external variable is defined is the storage space allocated.
• External variables can be assigned initial values as a part of variable definitions, but the values must be constants rather than expressions.
• If the initial value is not included then it is automatically assigned a value of zero.

Let us study global variables by a sample program given below:

/* Program to illustrate the use of global variables*/
# include <stdio.h>
int gv; /*global variable*/
main ( )
{
void function1(); /*function declaration*/
gv = 10;
printf (“%d is the value of gv before function call\n”, gv);
function1( );
printf (“%d is the value of gv after function call\n”, gv);
}
void function1 ( )
{
gv = 15:
}
OUTPUT

10 is the value of gv before function call
15 is the value of gv after function call

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: