C++ Programming/Scope/Examples/Confusing Scope Program

// Confusing Scope Program
#include <iostream>
 
using namespace std;
 
int i = 5;           /* The first version of the variable 'i' is now in scope */
 
void p(){
  int i = -1;        /* A ''new'' variable, also called 'i' has come into existence. The 'i' declared above is now out of scope,*/
  i = i + 1;
  cout << i << ' ';  /* so this ''local'' 'i' will print out the value 0.*/
}                    /* The newest variable 'i' is now out of scope. The first variable, also called 'i', is in scope again now.*/
 
 
int main(){
  cout << i << ' ';  /* The first variable 'i' is still in scope here so a ''5'' will be output here.*/
  char ch;
  int i = 6;         /* A ''new'' variable, also called 'i' has come into existence. The first variable 'i' is now out of scope again,*/
  i = i + 1;
  p();
  cout << i << endl; /* so this line will print out a ''7''.*/
  return 0;
}                    /* End of program: all variables are, of course, now out of scope.*/
Last modified on 28 February 2010, at 22:09