prakharsingh95 prakharsingh95 - 3 months ago 15
C++ Question

Different behaviour of comma operator in C++ with return?

Consider the following:

#include <iostream>
int main() {
int x;
x = 2,3;
std::cout<<x<<"\n";
return 0;
}


This outputs 2.

Now consider this:

#include <iostream>
int f(){ return 2,3; }
int main() {
int x;
x = f();
std::cout<<x<<"\n";
return 0;
}


This outputs 3.

Why is the comma operator behaving differently?

(I am using
g++ 5.4.0
with
-std=c++14
to compile.)

Answer

According to the Operator Precedence, comma operator has lower precedence than operator=, so x = 2,3; is equivalent to (x = 2),3;.

Operator precedence determines how operator will be bound to its arguments, tighter or looser than other operators according to their precedences.

Note the comma expression is (x = 2),3 here, not 2,3. The expression x = 2 is evaluated at first (and its side effects are completed), then the result is discarded, then the expression of 3 is evaluated (it does nothing in fact). That's why the value of x is 2. Note that 3 is the result of the whole comma expression (i.e. x = 2,3), it won't be used to assign to x.

For return 2,3;, the comma expression is 2,3, the expression 2 is evaluated then its result is discarded, and then 3 is evaluated and returned as the result of the whole comma expression, which is returned by the return statement later.