Though we urge you not to program using this style, we are providing an
exercise that uses nested blocks to help you understand the scope rules.
Give the output that this code fragment would produce if embedded in an
otherwise complete, correct program.
{
int x = 1;
cout << x << endl;
{
cout << x << endl;
int x = 2;
cout << x << endl;
{
cout << x << endl;
int x = 3;
cout << x << endl;
}
cout << x << endl;
}
cout << x << endl;
}
It helps to slightly change the code fragment to understand to which declaration:
each usage resolves.
{
int x1 = 1;// output in this column
cout << x1 << endl;// 1<cr>
{
cout << x1 << endl;// 1<cr>
int x2 = 2;
cout << x2 << endl;// 2<cr>
{
cout << x2 << endl;// 2<cr>
int x3 = 3;
cout << x3 << endl;// 3<cr>
}
cout << x2 << endl;// 2<cr>
}
cout << x1 << endl;// 1<cr>
}
Here <cr > indicates that the output starts a new line.