Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does comma operator work during assignment?

Tags:

c

int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
  1. Is (1,2,3) some sort of structure in c++ (some primitive type of list, maybe?)
  2. Why is b assigned the value 3? Does the compiler simply take the last value from the list?
like image 447
conectionist Avatar asked Dec 23 '11 20:12

conectionist


3 Answers

Yes, that's exactly it: the compiler takes the last value. That's the comma operator, and it evaluates its operands left-to-right and returns the rightmost one. It also resolves left-to-right. Why anyone would write code like that, I have no idea :)

So int b = (1, 2, 3) is equivalent to int b = 3. It's not a primitive list of any kind, and the comma operator , is mostly used to evaluate multiple commands in the context of one expression, like a += 5, b += 4, c += 3, d += 2, e += 1, f for example.

like image 98
Ry- Avatar answered Sep 28 '22 15:09

Ry-


(1,2,3) is an expression using two instances of the comma operator. The comma operator evaluates its left operand, then there's a sequence point and then it evaluates its right operand. The value of the comma operator is the result of the evaluation of the right hand operand, the result of evaluating the left operand is discarded.

int b = (1,2,3);

is, therefore, equivalent to:

int b = 3;

Most compilers will warn about such a use of the comma operand as there is only ever a point to using a comma operator if the left hand expression has some side effect.

like image 22
CB Bailey Avatar answered Sep 28 '22 13:09

CB Bailey


The second line is using the comma operator. An expression like

a, b

evaluates both a and b and returns b.

In this case, the second line is parsed like:

int b = ((1, 2), 3);

so (1, 2) is evaluated (to 2) then thrown away, and the end result is simply 3.

like image 34
Paolo Capriotti Avatar answered Sep 28 '22 14:09

Paolo Capriotti