Declarations/definitions as statements in C and C++

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

    In C++ declarations are statements while in C declarations are not statements. So according to the C grammar in this for loop

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

    int a = 5; must be a substatement of the loop. However it is a declaration.

    You could make the code to be compiled in C by using the compound statement as for example

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

    though the compiler can issue a diagnostic message saying that the variable a is not used.

    One more consequence that in C declarations are not statements. You may not place a label before a declaration in C. For example this program

    #include 
    
    int main(void) 
    {
        int n = 2;
    
        L1:
        int x = n;
    
        printf( "x == %d\n", x );
    
        if ( --n ) goto L1; 
    
        return 0;
    }
    

    does not compile in C though it compiles as a C++ program. However if to place a null-statement after the label then the program does compile.

    #include 
    
    int main(void) 
    {
        int n = 2;
    
        L1:;
        int x = n;
    
        printf( "x == %d\n", x );
    
        if ( --n ) goto L1; 
    
        return 0;
    }
    

提交回复
热议问题