Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the following code:

int main() {
   int i, j;

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

   cout << i;

   return 0;
}

The output is 1010.

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

like image 880
Anon Avatar asked Dec 05 '22 08:12

Anon


2 Answers

The comma operator is a sequence point: as it says in the C++17 standard for example,

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.

Thus, the effect of the ++ operator is guaranteed to occur before 999+j is evaluated.

like image 82
Brian Bi Avatar answered Dec 26 '22 23:12

Brian Bi


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

No. The postfix operator evaluates to the value of the old j and has the side effect of incrementing j.

Comma operator evaluates the second operand after the first operand is evaluated and its side-effects are evaluated.

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.

https://stackoverflow.com/a/7784819/2805305

like image 32
bolov Avatar answered Dec 27 '22 01:12

bolov