6

Possible Duplicate:
why does 3,758,096,384 << 1 gives 768

Today I found out that following code compiles with gcc:

#include <iostream>

int main()
{
    int x = (23,34);

    std::cout << x << std::endl; // prints 34

    return 0;
}

Why does this compiles? What is the meaning of (..., ...)?

Community
  • 1
  • 1
pwks
  • 71
  • 6

2 Answers2

14

In an expression, the comma operator will evaluate all its operands and return the last. That's why in your example, x is equal to 34.

David G
  • 94,763
  • 41
  • 167
  • 253
8

In C++, , is an operator, and therefore (23,34) is an expression just like (23+34) is an expression. In the former, , is an operator, while in the latter, + is an operator.

So the expression (23,34) evaluates to the rightmost operand which is 34 which is why your code outputs 34.

I would also like to mention that , is not an operator in a function call:

int m = max(a,b);

Here , acts a separator of arguments. It doesn't act as operator. So you pass two arguments to the function.

However,

int m = max((a,b), c);

Here first , is an operator, and second , is a separator. So you still pass two arguments to the function, not three, and it is equivalent to this:

int m = max(b, c); //as (a,b) evaluates to b

Hope that helps. :-)

Nawaz
  • 353,942
  • 115
  • 666
  • 851