编译器如何根据优先级和关联性解释此表达式

How does the compiler interpret this expression, in terms of Precedence and Associativity?

本文关键字:关联性 解释 表达式 优先级 何根 编译器      更新时间:2023-10-16

这是C++入门5th的练习:

Exercise 4.33: Explain what the following expression does(Page158):
someValue ? ++x, ++y : --x, --y

代码:

bool someVlaue = 1;
int x = 0;
int y = 0;
someVlaue ? ++x, ++y : --x,--y;
std::cout << x << std::endl << y << std::endl;

我尝试了Gcc4.81Clang3.5,都给了我:

1
0
Press <RETURN> to close this window...

为什么不11?谁能解释一下它是如何解释的?

由于逗号运算符的优先级非常低,因此表达式

someValue ? ++x, ++y : --x,--y;

相当于:

(someValue ? ++x, ++y : --x),--y;

因此,执行++x, ++y表达式(将xy设置为 1),然后在末尾执行表达式--y,将y恢复为 0。

注意 - 逗号运算符引入了序列点,因此多次修改y不会产生未定义的行为。

表达式

someValue ? ++x, ++y : --x, --y

被评估为

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

如您所见,y被修改了两次,一次递增,一次递减,因此结果是1 0而不是1 1