c ++表达式值(运算符优先级)

sch*_*llr 2 c++ conditional-operator operator-precedence prefix-operator

以下表达式:-

int main()
{
    int x=2, y=9;
    cout << ( 1 ? ++x, ++y : --x, --y);
}
Run Code Online (Sandbox Code Playgroud)

给出以下输出:-

9
Run Code Online (Sandbox Code Playgroud)

根据我的理解,它应该返回 ++y,它应该是 10。出了什么问题?

Ruk*_*uks 5

与逗号运算符 ( )相比,三元运算符 ( ?and :) 具有更高的优先级,。因此,首先评估三元条件语句中的表达式,然后使用逗号运算符拆分语句。

1 ? ++x, ++y : --x, --y

本质上变成

   (1 ? (++x, ++y) : (--x)), (--y)
/* ^^^^^^^^^^^^^^^^^^^^^^^^ is evaluated first by the compiler due to higher position in
                            the C++ operator precedence table */
Run Code Online (Sandbox Code Playgroud)

您可以通过简单地将表达式括在括号中来消除该问题:

1 ? (++x, ++y) : (--x, --y)

这会强制编译器首先计算括号内的表达式,而不考虑运算符的优先级。