Local and External Variables In C
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 disappearswhen 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.
0 comments:
Post a Comment