1

Consider the following snippet:

int a, b, c;
a = (b = 3, c = 4, 5, 6);

It turns out that, after those lines are executed, b has the value 3, c has the value 4. Nothing unexpected so far. But a has value 6. Why is that?

Also, does this have an useful use?

Paul92
  • 8,827
  • 1
  • 23
  • 37

2 Answers2

6

Because the , operator discards all the operands to the left, and since 6 is the rightmost operand, it's the only one which is not discarded.

This is from ยง 6.5.17 n1570 draft

  1. The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

  2. EXAMPLE As indicated by the syntax, the comma operator (as described in this subclause) cannot appear in contexts where a comma is used to separate items in a list (such as arguments to functions or lists of initializers). On the other hand, it can be used within a parenthesized expression or within the second expression of a conditional operator in such contexts. In the function call

    f(a, (t=3, t+2), c)
    

    the function has three arguments, the second of which has the value 5.

You can read more here

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

Whenever you use a separator (i.e. ',') in an assignment statement, it assigns a value that is in the last. For example
int i = (2,3); // i = 3; variable i get the value of 3 not 2.

Waqas Shabbir
  • 755
  • 1
  • 14
  • 34