If you declare a variable outside all functions, the variable has external visibility; every function that follows the declaration can see the variable. External vari-ables are called “global” in some other languages.
Experienced C programmers use external variables only when necessary—for instance, when two or more functions need the ability to change the same variable or communicate with each other by changing a variable. Even in those cases, however, you may be able to avoid the dangers of external visibility by passing a pointer to the variable as a function argument. For more information, see “Passing Pointers to Functions”.
Most external variables are declared near the beginning of the program, before any function definitions. In this way, you can make the variable visible to every function in the program. You could do this in VISIBLE1.C by placing the declaration of val,
int val = 10;
immediately before the main function.
If you declare the variable val later in the program, it is not visible to functions that precede the declaration. The VISIBLE2.C program below demonstrates this principle.
/* VISIBLE2.C: Demonstrate external visibility. */
#include <stdio.h>
void be_bop( int param );
main()
{
be_bop( val ); /* Error! */
}
int val = 10;
void be_bop( int param )
{
printf( "val = %d\n", param );
}
The VISIBLE2.C program is identical to VISIBLE1.C except that val is
declared externally
int val = 10;
following the main function, rather than locally within main.
Because the declaration occurs outside all functions, the variable is external. However, because the declaration follows the main function, the variable is not visible within main. When the printf statement in the main function refers to val, QuickC issues the error message:
C2065: 'val' : undefined
Remember, QuickC reads the program line by line, from start to finish. Since the compiler knows nothing about val when it reaches the reference in main, it must treat val as undefined. In this program, only the be_bop function can refer to val.