Post-增量运算符行为 w.r.t 逗号运算符?

Post-increment operator behaviour w.r.t comma operator?

在下面的代码中:

int main() {
   int i, j;

   j = 10;
   i = (j++, j+100, 999+j);

   cout << i;

   return 0;
}

输出为1010

但是不应该是 1009,因为 ++ 应该在使用整个表达式之后完成?

++ should be done after the whole expression is used?

没有。后缀运算符计算旧 j 的值并具有递增 j.

的副作用

逗号运算符计算第二个操作数在计算第一个操作数及其副作用之后

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded- value expression (Clause 5)83. Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.

逗号运算符是一个序列点:例如,如 C++17 标准所述,

Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression.

因此,++ 运算符的效果保证在计算 999+j 之前发生。

逗号运算符的结合性从左到右。

所以从j++开始,这个会先求值(j变成11

然后j + 100求值(没用)

然后计算 999 + j 等于 1010

这个最右边的值被分配给 i

因此,输出为1010

长答案:

内置逗号运算符

The comma operator expressions have the form

E1 , E2   

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).

这已经回答了您的问题,但我将参考您的代码逐步完成:

从简单的开始,例如

int value = (1 + 2, 2 + 3, 4 + 5); // value is assigned 9

因为...表达式E1被求值,其结果被丢弃...这里,由于我们有2个以上的操作数,逗号运算符的结合性也来了开始玩了。

However shouldn't it be 1009, as '++" should be done after the whole expression is used?

现看:

int j = 0;
int i = (j++, 9 + j);

此处,i 的值为 10,因为 ...及其副作用在表达式 E2 的计算开始之前完成... 因此, j 的递增在 9 + j.

的计算之前生效

我想你现在可以清楚地理解为什么你的

j = 10;
i = (j++, j+100, 999+j);

i 赋值为 1010.