int x = 0;
int y = 2;
int z = (++x, ++y);
I get that z is 3 because the value is taken from ++y, but why is ++y being chosen?
int x = 0;
int y = 2;
int z = (++x, ++y);
I get that z is 3 because the value is taken from ++y, but why is ++y being chosen?
It's called comma operator
. It evaluates ++x
(now x is 1), then evaluates ++y
(now y is 3) and assign value of y to
z``
The ``comma operator groups left-to-right. § 5.18
A pair of expressions separated by a comma is evaluated left-to-right and the value of the left expression is discarded.
Because (++x,++y) evaluates ++x
first, then ++y
and whatever was evaluated last is returned and assigned to z
.
This uses comma operator. The equivalent is:
int x = 0;
int y = 2;
++x; // or x = x + 1;
++y; // or y = y + 1;
int z = y;