Declarations/definitions as statements in C and C++

后端 未结 4 1972
遇见更好的自我
遇见更好的自我 2021-02-03 18:28

I was confused when this wouldn\'t compile in C:

int main()
{
    for (int i = 0; i < 4; ++i)
        int a = 5; // A dependent statement may not be declarati         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-03 18:47

    C++ allowed that the "substatement" of an iteration statement was implicitly a compound statement ([stmt.iter])

    If the substatement in an iteration-statement is a single statement and not a compound-statement, it is as if it was rewritten to be a compound-statement containing the original statement. Example:

    while (--x >= 0)
       int i;
    

    can be equivalently rewritten as

    while (--x >= 0) {
       int i;
    }
    

    the C standard does not have this language.

    Additionally, the definition of a statement changed in C++ to include a declaration statement, so even if the above change wasn't made, it would still be legal.


    The reason that adding braces makes it work is because your declaration now becomes a compound-statement which can include declarations.

    You are allowed to have an identifier in a loop body without braces, so you can do this instead:

    int a = 5;
    for (int i = 0; i < 4; ++i)
        a;
    

提交回复
热议问题