Reputation: 68598
In C++ std 3.3.1p4:
Given a set of declarations in a single declarative region, each of which specifies the same unqualified name, they shall all refer to the same entity.
In the following, aren't the two int
declarations in the same declarative region, specify the same unqualified name, and refer to two different entities?
int main()
{
int i;
{
int i;
}
}
How does the quote not apply and render this ill-formed?
If the quote doesn't apply to this, what does it apply to?
(Note that the declarative region of the first i
does include the second i
as demonstrated in the example in 3.3.1p2.)
Upvotes: 1
Views: 268
Reputation: 881153
They are not in the same single declarative region. The declarative region of the inner i
is limited to within the innermost braces.
In fact 3.3.1/2
has code remarkably similar to your own:
int j = 24;
int main() {
int i = j, j;
j = 42;
}
In that, the j
used to set i
is the 24
one but the scope of that outer j
stops after the ,
and restarts at the }
. Those two j
variables are distinct despite the fact they're in the file declarative region for the same reasons as your example: the re are two declarative regions.
Since there is not a single declarative region, scope takes control. C++11 3.3.1/1
states (my bold):
Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid, that is, in which that name may be used as an unqualified name to refer to the same entity. In general, each particular name is valid only within some possibly discontiguous portion of program text called its scope.
The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (containing) declarative region.
It's the possibly discontiguous
that's important here, the inner i
(in your example) "descopes", or hides, the outer i
even though the outer declarative region may enclose the inner one.
Upvotes: 3