2
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?

user3029760
  • 165
  • 4
  • 7

3 Answers3

3

It's called comma operator. It evaluates ++x(now x is 1), then evaluates ++y(now y is 3) and assign value of y toz``

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.

billz
  • 44,644
  • 9
  • 83
  • 100
2

Because (++x,++y) evaluates ++x first, then ++y and whatever was evaluated last is returned and assigned to z.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

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;
klm123
  • 12,105
  • 14
  • 57
  • 95