[cs23021-2] on scope

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Feb 16 15:10:54 EST 2010


CSI students,

This is to clarify the scoping rules. The definition is that the
variable's scope is inside the block it is declared in, from the place
of declaration until the end of the block. C++ allows variables with
the same name to be declared in different blocks. The blocks may
overlap (one block may be inside the other). In this case the outer
variable is not available while the inner one is in scope.

As an illustration. This program
--------------
// demonstrating usage of scope of variables
// Mikhail Nesterenko
// 2/16/2010

#include <iostream>

using namespace std;

int main(){
    int i=1;
    while(i < 5){
    	i++; cout << "i=" << i << endl;  // outer variable
	{
	    i++; cout << "i=" << i << endl; // still outer variable
	    int i=1;
	    i--; cout << "i=" << i << endl; // inner variable
        }
   }
}
---------------------------------
produces this output
---------------------------------
i=2
i=3
i=0
i=4
i=5
i=0
---------------------------------


Thanks,
--
Mikhail


More information about the cs23021-2 mailing list