My questions is:
Why is the (void)
responsible to return a different value? What's exactly happening?
struct S {
int operator,(int) { return 0; }
};
std::cout << (S(), 42) << '\n'; // prints '0'
std::cout << ((void) S(), 42) << '\n'; // prints '42'
Problem here is that comma operator has been overloaded.
So first line:
(S(), 42)
Will invoke this custom overload of comma operator, since arguments are S
and int
which matches this overload. Note this version always returns 0
value.
In second line:
((void) S(), 42)
Your custom overload of comma operator doesn't match type passed, since first argument is type of void
(casting is done). So build-in version of comma operator kicks in. This means that second argument will be returned. That it is why in second line 42 is printed.
Side note:
(void)
is performing explicit conversion (to void
).
For the 1st case S(), 42
, the S::operator,
will be invoked on temporary S
(i.e. S()
) and return the value 0
.
For the 2nd case, the temporary S
is converted to void
explicitly, so for (void) S(), 42
the built-in comma operator will be invoked instead, as the effect the 2nd operand 42
will be returned by comma operator and then printed out. (The 1st operand (void) S()
is evaluated firstly and the result is discarded.)
The type, value, and value category of the result of the comma expression are exactly the type, value, and value category of the second operand
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With