Mega Code Archive

 
Categories / C++ Tutorial / Language Basics
 

A scoping example

#include <iostream> using std::cout; using std::endl; void useLocal( void );  void useStaticLocal( void );  void useGlobal( void );  int x = 1; int main() {    int x = 5;    cout << x << endl;    {       int x = 7;       cout << "local x in main's inner scope is " << x << endl;    }    cout << x << endl;    useLocal();     useStaticLocal();     useGlobal();     useLocal();     useStaticLocal();     useGlobal();     cout << x << endl;    return 0; }  void useLocal( void ) {    int x = 25;    cout << "local x is " << x << " on entering useLocal" << endl;    x = x + 20;    cout << "local x is " << x << " on exiting useLocal" << endl; }  void useStaticLocal( void ) {    static int x = 50;    cout << "local static x is " << x << " on entering useStaticLocal"        << endl;    x = x + 20;    cout << "local static x is " << x << " on exiting useStaticLocal"        << endl; }  void useGlobal( void ) {    cout << "global x is " << x << " on entering useGlobal" << endl;    x = x + 20;    cout << "global x is " << x << " on exiting useGlobal" << endl; } 5 local x in main's inner scope is 7 5 local x is 25 on entering useLocal local x is 45 on exiting useLocal local static x is 50 on entering useStaticLocal local static x is 70 on exiting useStaticLocal global x is 1 on entering useGlobal global x is 21 on exiting useGlobal local x is 25 on entering useLocal local x is 45 on exiting useLocal local static x is 70 on entering useStaticLocal local static x is 90 on exiting useStaticLocal global x is 21 on entering useGlobal global x is 41 on exiting useGlobal 5