About the return value of (b, c)

I just want to write the code

1
2
// a, b, c are all int;
a = max(b,c);


However, I missed the max, and the code is:

a = (b,c);

The code ran as well. I wonder what the return value of (b, c) is.
It seems that the code is equivalent to

a = c;

Thanks very much if you can help me.
Last edited on
> It seems that the code is equivalent to a = c;

Yes. In (b,c), b is (evaluated and) discarded, the result of the expression is c

More information: https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator
Your observation is right.

The comma operator is a binary operator. It first evaluates its the first operand (b) and discards the result. After that it evaluates the second operand (c) and returns the result.

The comma operator is rarely used, but one place you might see it's used is if you want multiple increment expressions in a for loop.

1
2
3
4
5
for (int i = 1, j = 10; i <= j; ++i, --j)
{                               // ^ comma operator 
    std::cout << i << " " << j << "\n";
}
1 10
2 9
3 8
4 7
5 6


Note that not all commas are comma operators.

1
2
3
// These do NOT use the comma operator ...
a = max(b, c);
int i = 1, j = 10;
Thanks for your answers.
Topic archived. No new replies allowed.