Why does this ternary result in a pointer being printed?

4755 views c++ conditional-operator
11

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?

answered question

2 Answers

8

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* of the ostream << is selected. Both branches of the ternary conditional operator are no-ops.

posted this
5

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.

posted this

Have an answer?

JD

Please login first before posting an answer.