Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ comma operator puzzles me. Language lawyers?

Tags:

c++

visual-c++

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.]

like image 283
Jive Dadson Avatar asked Oct 04 '12 17:10

Jive Dadson


1 Answers

CASE 1:

i = 1,2;

= has higher precedence than ,

hence, 1 is assigned to i.

Since assignment evaluates to an lvalue in c++,(evaluates to rvalue in c) it becomes i,2 which evaluates to2 (refer NOTE)

CASE 2:

i = (1,2);

() has higher precedence than =

expressions or operands separated by , operator evaluates to the value of the last expression or operand hence, 2 is assigned to i


NOTE

a comma expression like 33,77,x,y,z is evaluated from left to right.

The result of such comma expression is the value of rightmost expression .

Examples

Consider, int z=100; 
then
1,4,5; //evaluates to 5
1,100,z+100; //evaluates to 200
like image 115
12 revs, 2 users 93% Avatar answered Oct 15 '22 13:10

12 revs, 2 users 93%