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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Magiczne
  • 1,586
  • 2
  • 15
  • 23

1 Answers1

8

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.

  • For first case, the second operand is evaluated and returned.
  • For second case, the third operand is evaluated and returned.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261