Is a declaration valid inside an if block with no actual block?

江枫思渺然 提交于 2019-12-21 07:57:08

问题


Is the following code valid? If so, what is the scope of x?

int main()
{
   if (true) int x = 42;
}

My intuition says that there is no scope created by the if because no actual block ({}) follows it.


回答1:


GCC 4.7.2 shows us that, while the code is valid, the scope of x is still simply the conditional.

Scope

This is due to:

[C++11: 6.4/1]: [..] The substatement in a selection-statement (each substatement, in the else form of the if statement) implicitly defines a block scope. [..]

Consequently, your code is equivalent to the following:

int main()
{
   if (true) {
      int x = 42;
   }
}

Validity

It's valid in terms of the grammar because the production for selection statements is thus (by [C++11: 6.4/1]):

selection-statement:
  if ( condition ) statement
  if ( condition ) statement else statement
  switch ( condition ) statement

and int x = 42; is a statement (by [C++11: 6/1]):

statement:
  labeled-statement
  attribute-specifier-seqoptexpression-statement
  attribute-specifier-seqoptcompound-statement
  attribute-specifier-seqoptselection-statement
  attribute-specifier-seqoptiteration-statement
  attribute-specifier-seqoptjump-statement
  declaration-statement
  attribute-specifier-seqopttry-block




回答2:


My Visual studio says that time of life of your variable x is pretty small - just while we are inside operator if, so x vill be destroyed when we are out of if condition, and there is absolutely no meaning to declare variables like this.



来源:https://stackoverflow.com/questions/15568959/is-a-declaration-valid-inside-an-if-block-with-no-actual-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!