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

Sad*_*ara 0 c++ label goto do-while

为什么标签不能紧邻}while(/*exp*/);do-while 循环之前放置,而不是期望主表达式。

\n
int main()\n{\n    \n    int x = 5;\n    \n    do{\n        if(x==2) goto label;\n        \n        printf("%d", x);\nlabel:\n        ; // if not error: expected primary-expression before \xe2\x80\x98}\xe2\x80\x99 token\n    }while(--x);\n\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Vla*_*cow 7

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

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

label:
        ;
    }while(--x);
Run Code Online (Sandbox Code Playgroud)

注意,最好重写 do while 语句,不要使用 goto 语句,例如

do{
    if ( x != 2 ) printf("%d", x);
}while(--x);
Run Code Online (Sandbox Code Playgroud)

还要记住,与 C++ 中的 C 声明相反,也是语句。因此,您可以在声明之前放置标签。