C++ 中 } 之前的预期主表达式

expected primary expression before } in C++

为什么不能在 do-while 循环中将标签直接放在 }while(/*exp*/); 之前,而不是期待主表达式。

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;
}

标签可以放在语句之前。符号 '}' 不表示语句。

因此您需要在标签之后和右大括号之前包含一个空语句。

label:
        ;
    }while(--x);

注意改写do while语句最好不要像

这样的goto语句
do{
    if ( x != 2 ) printf("%d", x);
}while(--x);

另请记住,在 C++ 声明中与 C 相对的也是语句。所以你可以在声明之前放置一个标签。

问题是标签是用来标记语句的。换句话说,没有后面的声明就不能有标签。分号相当于一个空语句,但 } 不表示语句。

label: /* semicolon for empty statement*/ ;