Quote:
Precedence Problems
The iostream library is designed to allow a minimum of parentheses:
cout << "a+b = " << a+b << endl;
The + operator has higher precedence than the left shift operator, so we get the desired parse; a+b is calculated first, then the result is sent to cout.
cout << a ? f() : g();
Here, the use of C++'s only ternary operator gets us into trouble, but it's not that ?: is ternary; it's that it has lower precedence than <<. Therefore, we're asking the compiler to generate code to shift a to cout, then use the result of that expression as the condition in the ?:. The tragic aspect of this situation is that the code is perfectly legal! (An output stream object like cout has a member operator void * that can be used implicitly to convert it to a void * value, which in turn can be converted to false or true, depending on whether the pointer value is null or not.) Here's a case where we reach for our parentheses:
cout << (a ? f() : g());
If you want to be considered completely normal, you can take things a step further:
if( a )
cout << f();
else
cout << g();
so a safer code would be...