int a,b;
a = 1 ? 1,2 : 3,4; // a = 2
b = 0 ? 1,2 : 3,4; // b = 3
Comma operator returns always the right side of comma, but if we make an assignment to variable it returns left except the case when we use (). So how the hell the first expression gives the 2.
I see it as a = 1,2 so it should be 1 but actually a=2.
Why?
Due to operator precedence (comma operator having least precedence), your code actually looks like
int a,b;
(a = 1 ? (1,2) : 3),4; // a = 2
(b = 0 ? (1,2) : 3),4; // b = 3
So, as per the ternary condition rule, quoting C11, chapter §6.5.15
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below. 110)
[...]
110) A conditional expression does not yield an lvalue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With