A scoping example : Variables « Language Basics « C++ Tutorial






#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








1.3.Variables
1.3.1.Assign value to a variable
1.3.2.Dynamic initialization.
1.3.3.A scoping example
1.3.4.Using the unary scope resolution operator
1.3.5.Finding maximum and minimum values for data types
1.3.6.Comparing data values