C++ if语句表示法 - 这是等价的吗?

Tha*_*Guy -2 c++ syntax if-statement

我99%肯定这不起作用,但剩下的1%困扰着我

    int x;

    //is this if statement

    if(x == 1, 5, 7)
    {
    //do something here
    }
    //equivalent to this if statement

    if((x == 1) || (x == 5) || (x == 7))
    {
    //do something here
    }
Run Code Online (Sandbox Code Playgroud)

πάν*_*ῥεῖ 5

不,它完全不相同.

if(x == 1, 5, 7)
Run Code Online (Sandbox Code Playgroud)

调用逗号运算符,由于,优先级最低,它将有效地结束最后一个值:

if(7)
Run Code Online (Sandbox Code Playgroud)

因为用括号展开应该看起来像

if(((x == 1), 5), 7)
Run Code Online (Sandbox Code Playgroud)

if((x == 1) || (x == 2) || (x == 7))
Run Code Online (Sandbox Code Playgroud)

检查是否x等于1,27.

  • 逗号运算符的优先级最低,请参见http://en.cppreference.com/w/cpp/language/operator_precedence和http://ideone.com/rxhki1 (2认同)