|
|
void f1() /* Function f1() that uses global var x */ { x = 4; /* ******** Access error !!!! ********* */ } int x; /* Definition of global var x */ void f2() /* Function f2() that uses global var x */ { x = 4; } |
How to run the program:
|
|
|
|
In other words:
|
|
void f1() /* Function f1() that uses global var x */ { x = 4; /* ******** Access error !!!! ********* */ } int x; /* Definition of global var x */ void f2() /* Function f2() that uses global var x */ { x = 4; } |
We can fix this problem by using a declaration of the variable x:
extern int x; /* ******** Declaration of x ********** */ void f1() /* Function f1() that uses global var x */ { x = 4; /* ******** Access error !!!! ********* */ } int x; /* Definition of global var x */ void f2() /* Function f2() that uses global var x */ { x = 4; } |
How to run the program:
|
|
|
Explanation:
|
double r = 3.14; int main( int argc, char* argv[] ) { printf( "r = %lf\n", r ); /* Uses "double r" */ int r = 4444; /* Shadows global variable double r ! */ printf( "r = %d\n", r ); /* Uses "int r" */ printf( "r = %lf (this will print weird stuff)\n", r ); } |
How to run the program:
|
|
File 1: global4a.c | File 2: global4b.c |
---|---|
|
#include <stdio.h> static double x; void func() { x = 12345; printf( "x = %lf\n", x ); /* uses "static double x" */ } |
When you compile these programs, you will get an error:
UNIX>> gcc -c global4a.c // No error UNIX>> gcc -c global4b.c // No error UNIX>> gcc global4a.o global4b.o // Error in linking loader phase Undefined first referenced symbol in file x global4a.o ld: fatal: Symbol referencing errors. No output written to a.out collect2: ld returned 1 exit status |
Explanation:
|
Note: try this
|
How to run the program:
|
|
public class demo { public static double x = 3.14; // Class variable public static void main( String[] args ) { int x = 4; // Shadows class variable x System.out.println(x); // Prints 4 } } |
public class demo { public static double x = 3.14; // Class variable public static void main( String[] args ) { int x = 4; // Shadows class variable x System.out.println(demo.x); // Prints 3.14 } } |
|