/* The scope of an identifier is that part of the program where that identifier is visible (i.e. known). {}s compose statement blocks and may contain declarations. An auto variable has block scope. It is only visible within the block in which it is declared. That means that it cannot be referenced outside of the block in which it is declared. An outer block identifier is visible unless an inner block has more locally declared usage of the identifier (redefining that identifier). In this case, the outer block identifier is hidden from the inner block. A variable declared outside of any block is extern (external) by default. This variable is visible at any point in the source file after its declaration. It may be hidden if redefined in a block. */ #include void scoping_1(); void scoping_2(); int z = 5; int main() { printf( "\n" ); printf( "z = %d\n", z ); printf( "\n" ); scoping_1(); scoping_2(); printf( "\n" ); printf( "z = %d\n", z ); printf( "\n" ); return 0; } void scoping_1() { int x = 0, y = 2; // declare y printf( "Scoping #1: z = %d\n", z ); x += y; // add 2 to x { int y = 3; // declare a new variable y x += y; // add 3 to x { int y = 7; // declare a new variable y x += y; // add 7 to x } x += y; // add 3 to x } x += y; // add 2 to x printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); return; } void scoping_2() { int x = 0, y = 2; // declare y printf( "Scoping #2: z = %d\n", z ); x += y; // add 2 to x printf( "#1\n" ); printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); { int y = 3; // declare a new variable y int x = 2; x += y; // add 3 to x printf( "#2\n" ); printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); { int y = 7; // declare a new variable y int x = 2; x += y; // add 7 to x printf( "#3\n" ); printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); } x += y; // add 3 to x printf( "#4\n" ); printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); } x += y; // add 2 to x printf( "#5\n" ); printf( "x = %d\n", x ); printf( "y = %d\n", y ); printf( "\n" ); return; }