5. SCOPE RULES The program part(s) in which a particular piece of code or a data value ( e.g. variable, function ) can be accessed is known as the piece-of-codeβs or variableβs scope.
6.
7. Variable Scope int g = 10; // global variable void main ( ) { clrscr( ); int m = 20; // function scope void func ( void ); { int b = 30; // local scope cout << β β <<b; cout<< β β << m; }
8. cout<< β β << g; cout<< β β<<m; cout<<ββ<< b; // incorrect since var. of block cout<<ββ << f; // incorrect var. of function func func ( ); getch (); } void func ( void ) { int f = 40; cout < < β β << f; cout << β β<< g; cout << β β<< m; // incorrect since var. of fn. main. }
10. FUNCTION SCOPE void global-fn ( void ); // global / file scope void main ( ) { void internal-fn ( void ); // fn. Scope for main void internalβfn-2 ( void ) // fn. Scope for main global-fn ( ); // can call global fn. internal-fn ( ); // fn. Of main internal-fn2( ); // fn. Of main sub-internal-fn ( ); // incorrect b/c outside the scope }
11. void global-fn( void ) { cout<<β this is a global fn β; } void internal-fn ( void ) { void sub-internal-fn ( void ); // fn. Scope of internal-fn cout<< β this is an internal fn. β; global-fn ( ); // can call global fn. sub-internal-fn( ); // can call b/c fn of internal-fn internal-fn-2 ( ); // incorrect b/c fn. of main } void sub-internal-fn ( void ) { cout<<β sub internal fnβ; }
12. void internal-fn-2 ( void ) { cout<< β internal β fn β2 β; } OUTPUT This is global fn. This is an internal fn. Global-fn sub-internal fn internal fn2
13. Example of same varibale name as Formal and Actual Parameters void main ( ) { clrscr( ); void same ( int ); int a = 50; same ( a ); cout<<β n β << a; getch(); } void same ( int a ) { a = 60; cout<< β β << a; }
14. Example of Local and Global variable having the same name. int a = 20; void main ( ) { int a = 50; cout << βlocal var a : β<<a; cout<< β global var a : β<< : : a; } OUTPUT: 50 20 NOTE: You need to use : : ( scope resolution operator to refer to Global variable