I'm currently trying to learn C++ from "Savitch - Absolute C++"
In Ch. 3 he gives the definition of a block:
"A block is some C++ code enclosed in braces."
And he gives the Scope Rule for Nested Blocks:
"If an identifier is declared as a variable in each of two blocks, one within the other, then these are two different variables with the same name.
One variable exists only within the inner block and cannot be accessed outside
the inner block. The other variable exists only in the outer block and cannot
be accessed in the inner block."
I thought I understood this, but then an exercise followed, asking to state the output of the following code fragment:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
{
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;
}
|
According to the given Scope Rule, I would say that "int x = 1" is in an
outer block, "int x = 2" in an inner block of the first block, and "int x = 3" in an inner block of the second block.
So, as far as I understand, when the second cout is executed, no x has been defined (int x = 1 is in the outer block and cannot be accessed from the inner block).
But I appear to be wrong: the output of the second cout is "1", so it references
the x in the outer block.
So I'm afraid there's something I misunderstand. I hope someone on this list can
shed some light on this.