Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which subclause of C++ standard prohibits redeclaration / redefinition in a same block?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading