I came across this bit of code in an example from the Boost documentation:
std::vector<int> input;
input += 1,2,3,4,5,6,7,8,9;
How cute. Boost has a template for operator+= that takes advantage of the fact that the comma is, under most circumstances, an operator. (Wisely, C++ does not allow a hackist to overload “operator,“.)
I like to write cute code too, so I played around some with the comma-operator. I found something that looks weird to me. What do you think the following code will print?
#include <iostream>
int main() {
int i;
i = 1,2;
std::cout << i << ' ';
i = (1,2);
std::cout << i << std::endl;
}
You guessed it. VC++ 2012 prints “1, 2”. What’s up with that?
[Edit: I should have been more precise. Should have said C++ does not allow operator “,” in a list of int’s to be overloaded. Or better yet, nothing. The ‘,’ operator can be overloaded for classes and enums.]
CASE 1:
i = 1,2;=has higher precedence than,hence,
1is assigned toi.Since assignment evaluates to an
lvalueinc++,(evaluates torvalueinc) it becomesi,2which evaluates to2(refer NOTE)CASE 2:
i = (1,2);()has higher precedence than=expressionsoroperandsseparated by,operator evaluates to the value of the lastexpressionoroperandhence,2is assigned toiNOTE
a
comma expressionlike33,77,x,y,zis evaluated from left to right.The result of such comma expression is the value of rightmost expression .
Examples