int a = 1;
int b = (1,2,3);
cout << a+b << endl; // this prints 4
(1,2,3)
some sort of structure in c++ (some primitive type of list, maybe?)b
assigned the value 3
? Does the compiler simply take the last value from the list?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.
(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.
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.
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