Search code examples
c++labeldo-whilegoto

expected primary expression before } in C++


Why a label can not be placed immediately before }while(/*exp*/); in a do-while loop, instead of expecting a primary expression.

int main()
{
    
    int x = 5;
    
    do{
        if(x==2) goto label;
        
        printf("%d", x);
label:
        ; // if not error: expected primary-expression before ‘}’ token
    }while(--x);

    return 0;
}

Solution

  • Labels may be placed before statements. The symbol '}' does not denote a statement.

    So you need to include a null statement after the label and before the closing brace.

    label:
            ;
        }while(--x);
    

    Pay attention to that it is better to rewrite the do while statement without the goto statement like

    do{
        if ( x != 2 ) printf("%d", x);
    }while(--x);
    

    Also bear in mind that opposite to C in C++ declarations are also statements. So you may place a label before a declaration.