Conditional operator used in cout statement

The ?: operator has lower precedence than the << operator i.e., the compiler interprets your last statement as:

(std::cout << (a != 0)) ? 42.0f : -42.0f;

Which will first stream the boolean value of (a!=0) to cout. Then the result of that expression (i.e., a reference to cout) will be cast to an appropriate type for use in the ?: operator (namely void*: see cplusplus.com), and depending on whether that value is true (i.e., whether cout has no error flags set), it will grab either the value 42 or the value -42. Finally, it will throw that value away (since nothing uses it).

Leave a Comment