Handout 9e

Referencing Variables in Enclosing blocks


Example 1

#include <iostream.h>

class classy {
	public:
		int x;
};

int x = 1;

int main() {

	classy A;

	{
		int x;

		::x = 1;
		A.x = 2;
		x = 3;

		cout << ::x << endl; //output the global
		cout << A.x << endl; // output the one in the enclosing block
		cout << x << endl; // output the one in this block
	}

	return 0;
}

Example 2

#include <iostream.h>

int x = 1;

namespace outer {
	int x;
}

int main() {

	outer::x = 2;
	
	{
		int x;

		::x = 1;
		outer::x = 2;
		x = 3;

		cout << ::x << endl; //output the global
		cout << outer::x << endl; // output the one in the enclosing block
		cout << x << endl; // output the one in this block
	}

	return 0;
}