声明在没有实际块的if块内有效吗?

Lig*_*ica 11 c++ language-lawyer

以下代码是否有效?如果是这样,范围是x什么?

int main()
{
   if (true) int x = 42;
}
Run Code Online (Sandbox Code Playgroud)

我的直觉说没有创建范围if因为没有实际的block({})跟随它.

Lig*_*ica 25

GCC 4.7.2告诉我们,虽然代码有效,但范围x仍然只是有条件的.

范围

这是因为:

[C++11: 6.4/1]: [..]在该子语句选择语句(每个子语句,在else所述的形式if语句)隐式地定义的块范围.[..]

因此,您的代码等同于以下内容:

int main()
{
   if (true) {
      int x = 42;
   }
}
Run Code Online (Sandbox Code Playgroud)

合法性

它在语法方面是有效的,因为选择语句的生成因此(通过[C++11: 6.4/1]):

选择语句:
  if(条件)语句
  if(条件)声明 else 语句
  switch(条件)声明

并且int x = 42;是一份声明(by [C++11: 6/1]):

statement:
  labeled-statement
  attribute-specifier-seq opt expression-statement
  attribute-specifier-seq opt compound-statement
  attribute-specifier-seq opt selection-statement
  attribute-specifier-seq opt iteration-statement
  attribute-specifier-seq opt jump-statement
  声明语句
   attribute-specifier-seq opt try-block

  • @Downvoter:请解释为什么你认为这个答案是不正确的.我期待听到你的意见.谢谢. (7认同)