Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this ternary result in a pointer being printed?

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?

like image 460
Elusivehawk Avatar asked Dec 04 '22 17:12

Elusivehawk


2 Answers

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.

like image 174
mch Avatar answered Dec 24 '22 17:12

mch


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.

like image 33
Bathsheba Avatar answered Dec 24 '22 17:12

Bathsheba