Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ What does 'int x = (anyInt1, anyInt2);' mean? [duplicate]

Tags:

c++

syntax

int

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 (..., ...)?

like image 350
pwks Avatar asked Nov 03 '12 12:11

pwks


2 Answers

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.

like image 160
David G Avatar answered Oct 13 '22 20:10

David G


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. :-)

like image 8
Nawaz Avatar answered Oct 13 '22 21:10

Nawaz