Chapter 6: C Functions and Program Structures
he int i declared
ions in it from other files, but you
annot use an external variable declared in another file.
There is a difference in the definition and the declaration of external variables. If
you use the extern keyword as in:
extern int tramp;
you have declared that tramp will be an int, but you have not defined it. To use
tramp you must define it in each file that will use it. Something like:
int tramp = NULL;
This must appear in a source file that uses it. For example:
In file1:
extern double gadabout;
extern char harlot;
In file2:
double gadabout = 0;
char harlot = ‘?’;
In this case changes to gadabout and harlot in file1 will also appear in file2 and
visa versa. Maybe I’m being harsh calling them tramp, gadabout, and harlot, but
externs are even more prone to being who-knows-where and doing who-knows-
what than regular external variables so they are bug prone.
Scope
Variable names have scope, meaning the locations where they are recognized, that
determine how they can be used.
Variable names declared in a function are recognized only in that particular
function. For example, you can have multiple functions with t
local to that function and they won’t interfere with each other. Likewise, a
variable declared within a block remains local to that block.
External variables have scope from the point they are declared to the end of the
text file. If you compile a file, you can call funct
c