Global variables are defined or declared outside every function scope:
extern int x; // A global variable defined in another program file int y = 4; // A global variable void f( ) { int y = 7; x = y + 3; } int main( int argc, char* argv[] ) { f( ); printf( "%d %d\n", x, y ); } |
Global variables are accessible (= can be used) in statements in any C program file
The lexical scope (or scope) of a global variable is:
extern int x; // A global variable defined in another program file int y = 4; // A global variable <- Scope of y starts here void f( ) { int y = 7; // Overshadows global var y x = y + 3; // Uses y = 7 } int main( int argc, char* argv[] ) { f( ); printf( "%d %d\n", x, y ); // Uses y = 4 } <- Scope of y ends here |
•
Scope
starts at the
definition
or
declaration
•
Scope
ends
at
the end of the
C program file
•
Global variables
can be
overshadowed
by
a
local variable
with the
same
variable name
Declarations of global variables can be written inside a function:
#include <stdio.h> int x; void f( ) { extern int y; // Local declaration of global variable y x = y + 3; } int y = 4; // Global variable int main( int argc, char* argv[] ) { f( ); printf( "%d %d\n", x, y ); } |
Scoping rule: a local declaration follows the same scoping rules of local variables !
DEMO: demo/C/set1/scope-declare.c
Example that shows that a localized declaration obeys the scoping rule for local variables:
#include <stdio.h> int x; void f( ) { { extern int y; // Scope of the declaration } x = y + 3; // Error: y is undeclared ! } int y = 4; // Global variable int main( int argc, char* argv[] ) { f( ); printf( "%d %d\n", x, y ); } |
The scope of declaration of variable y ended in the inner scope !!
DEMO: demo/C/set1/scope-declare.c (edit and re-compile)
|
Example where a global variable has not (yet) been defined or declared when you used it:
extern int x; // A global variable defined in another program file void f( ) { x = y + 3; // Use of y outside it's scope <---- Compile error } int y = 4; // Global variable // Scope of y starts here int main( int argc, char* argv[] ) { printf( "%d %d\n", x, y ); } |
When
y
was used, the
variable definition
was not yet processed !
Remember that the
C-compiler is
1-pass compiler !!!
DEMO: demo/C/set1/scoping-err2.c (edit and re-compile)
Example where a global variable is overshadowed by a local variable:
extern int x; // A global variable defined in another program file int y = 4; // A global variable <- Scope of y starts here void f( ) { int y = 7; // Overshadows global var y x = y + 3; // Uses y = 7 // Uses the local variable } int main( int argc, char* argv[] ) { f( ); printf( "%d %d\n", x, y ); // Uses y = 4 } <- Scope of y ends here |
If the intention was to use the global variable (int y = 4), then the program is in error.