Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: How does this inline if get parsed?

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?

like image 922
Paul Manta Avatar asked Dec 28 '22 20:12

Paul Manta


1 Answers

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/

like image 91
Lou Franco Avatar answered Jan 13 '23 10:01

Lou Franco