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