Consider this code:
int main()
{
cout << true ? "Yes" : "No";
return 0;
}
Its output will be 1
, not Yes
or No
. Why is it that true
is sent to the output stream instead of the Yes
or No
strings? How does the rest of the inline if get parsed?
It has to do with order of operations. It's the same as:
(cout << true) ? "Yes" : "No";
cout << true
returns an ostream&
, which must have a conversion to bool or an equivalent. The result of ?:
is thrown away.
If this seems odd (why this precedence?), just remember that ostream's operator<<
is an overload introduced in C++ code, which doesn't allow precedence changing. The precedence of <<
is designed for what makes sense for bit-shifting. Its use as a streaming operator came much later.
Edit: Probably converting to (void*)
using this: http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/
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