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?
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?
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.
++
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.
Associativity of the comma operator is left to right.
So starting from j++
, this will be evaluated first (j
becomes 11
)
Then j + 100
is evaluated (no use)
Then 999 + j
is evaluated which is equal to 1010
This rightmost value is assigned to i
Thus, the output is 1010
Long Answer:
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).
This already answers your question, but I'll walk through it with reference to your code:
Start with something simple like
int value = (1 + 2, 2 + 3, 4 + 5); // value is assigned 9
Because ...the expression E1 is evaluated, its result is discarded... Here, since we have more than 2 operands, the associativity of the comma operator also comes into play.
However shouldn't it be 1009, as '++" should be done after the whole expression is used?
Now see:
int j = 0;
int i = (j++, 9 + j);
Here, the value of i
is 10 because ...and its side effects are completed before evaluation of the expression E2 begins... Hence, the incrementation of j
has its effect before the evaluation of 9 + j
.
I think now you can clearly understand why your
j = 10;
i = (j++, j+100, 999+j);
i
is assigned a value of 1010.