Possible Duplicate:
C comma operator
I came across a line of code which I couldn't understand. I remember seeing something similar somewhere.
int x,y,z;
x=(y=2,z=2*y,z+4);
I know that the value assigned to x is 8. Can someone explain me why?
Possible Duplicate:
C comma operator
I came across a line of code which I couldn't understand. I remember seeing something similar somewhere.
int x,y,z;
x=(y=2,z=2*y,z+4);
I know that the value assigned to x is 8. Can someone explain me why?
This is equivalent to:
y = 2; // y == 2
z = 2 * y; // z == 4
x = z + 4; // x == 8
The operands of the comma operator are evaluated from left to right and the result is the value of the right operand.
the comma operator separates the previous values, and the last item in the comma is returned as the result, e.g.
a = b,c
assings the value of c to a. The parentheses here do essentially nothing, btw
So you have two assignments, then a statement, whose result is returned and assigned to x