This ternary, when used as-is, spits out a pointer:
std::stringstream ss;
ss << pair.second ? pair.second->toString() : "null";
std::cout << ss.str() << '\n';
This is a sample output:
{
"glossary": 000002B96B321F48
}
But when I surround the ternary operator in parenthesis, it works properly and gives me either the contents of toString() or "null".
ss << (pair.second ? pair.second->toString() : "null");
Also, expanding it to a proper if/else fixes it as well:
if (pair.second)
{
ss << pair.second->toString();
}
else
{
ss << "null";
}
What's going on?
https://en.cppreference.com/w/cpp/language/operator_precedence
<<
has a higher precedence than ?
ss << pair.second ? pair.second->toString() : "null";
is grouped as (ss << pair.second) ? pair.second->toString() : "null";
(ss << pair.second)
evaluates to the state of the stream, which is normally true
, so pair.second->toString()
will be evaluated and the result discarded.
The expression
ss << pair.second ? pair.second->toString() : "null"
is grouped as
(ss << pair.second) ? pair.second->toString() : "null"
pair.second
is a pointer, and the const void*
overload of the ostream
<<
is selected. Both branches of the ternary conditional have no effect on the output.
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