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

前端 未结 2 1829
醉话见心
醉话见心 2021-02-20 08:44

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 i

2条回答
  •  情深已故
    2021-02-20 09:15

    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-seqopt expression-statement
      attribute-specifier-seqopt compound-statement
      attribute-specifier-seqopt selection-statement
      attribute-specifier-seqopt iteration-statement
      attribute-specifier-seqopt jump-statement
      declaration-statement
      attribute-specifier-seqopt try-block

提交回复
热议问题