I’m reading Standard for Programming Language C++ and I cannot find a subclause prohibiting code like follows, which will obviously not compile:
/* Code A */
int main() {
int i;
int i;
}
while this one will compile:
/* Code B */
int main() {
int i;
{ int i; }
}
I’ve found something related, but I failed to find a matching one:
[basic.def.odr#1]: No translation unit shall contain more than one definition of any variable…
If it’s this subclause, I cannot find a subclause explaining why the 2 i‘s are not the same variable in Code B but are the same variable in Code A;
[basic.scope.block#1]:A name declared in a block ([stmt.block]) is local to that block; it has block scope. Its potential scope begins at its point of declaration ([basic.scope.pdecl]) and ends at the end of its block. A variable declared at block scope is a local variable.
In fact I tried to look for something like or more general than "A name of variable with a block scope cannot be redeclared within its potential scope, excluding nested blocks" like [temp.local#6], but I failed:
[temp.local#6]: The name of a template-parameter shall not be redeclared within its scope (including nested scopes). …
So can some give me some help? Thanks!
>Solution :
You are looking for [basic.scope.scope]/2
Unless otherwise specified:
- The smallest scope that contains a scope S is the parent scope of S.
- No two declarations (re)introduce the same entity.
- A declaration inhabits the immediate scope at its locus ([basic.scope.pdecl]).
- A declaration’s target scope is the scope it inhabits.
- Any names (re)introduced by a declaration are bound to it in its target scope.
An entity belongs to a scope S if S is the target scope of a declaration of the entity.
emphasis mine