Monday, January 26, 2009

Local and External Variables in C Program

If we say
f( ) {
int x;
...
}
g( ) {
int x;
...
}

each x is local to its own routine -- the x in f is unrelated to the x in g. (Local variables are also called ``automatic''.) Furthermore each local variable in a routine appears only when the function is called, and disappears when the function is exited. Local variables have no memory from one call to the next and must be explicitly initialized upon each entry. (There is a static storage class for making local variables with memory; we won't discuss it.)
As opposed to local variables, external variables are defined external to all functions, and are (potentially) available to all functions. External storage always remains in existence. To make variables external we have to define them external to all functions, and, wherever we want to use them, make a declaration.

main( )
{
extern int nchar, hist[ ];
...
count( );
...
}

count( )
{
extern int nchar, hist[ ];
int i, c;
...
}

int hist[129]; /* space for histogram */
int nchar; /* character count */

Roughly speaking, any function that wishes to access an external variable must contain an extern declaration for it. The declaration is the same as others, except for the added keyword extern. Furthermore, there must somewhere be a definition of the external variables external to all functions.
External variables can be initialized; they are set to zero if not explicitly initialized. In its simplest form, initialization is done by putting the value (which must be a constant) after the definition:

int nchar 0;
char flag 'f';
etc.

This is discussed further in a later section.
This ends our discussion of what might be called the central core of C. You now have enough to write quite substantial C programs, and it would probably be a good idea if you paused long enough to do so. The rest of this tutorial will describe some more ornate constructions, useful but not essential.

No comments:

Post a Comment