Declarations/definitions as statements in C and C++

后端 未结 4 1976
遇见更好的自我
遇见更好的自我 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 19:02

    According to cppreference, C++ includes following types of statements:

    1. expression statements;
    2. compound statements;
    3. selection statements;
    4. iteration statements;
    5. jump statements;
    6. declaration statements;
    7. try blocks;
    8. atomic and synchronized blocks

    While C considers following types of statements:

    1. compound statements
    2. expression statements
    3. selection statements
    4. iteration statements
    5. jump statements

    As you can notice, declarations are not considered statements in C, while it is not this case in C++.

    For C++:

    int main()
    {                                     // start of a compound statement
        int n = 1;                        // declaration statement
        n = n + 1;                        // expression statement
        std::cout << "n = " << n << '\n'; // expression statement
        return 0;                         // return statement
    }                                     // end of compound statement
    

    For C:

    int main(void)
    {                          // start of a compound statement
        int n = 1;             // declaration (not a statement)
        n = n+1;               // expression statement
        printf("n = %d\n", n); // expression statement
        return 0;              // return statement
    }                          // end of compound statement
    

提交回复
热议问题