Conditional operator used in cout statement

*爱你&永不变心* 提交于 2019-11-28 01:51:58

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 http://www.cplusplus.com/reference/iostream/ios/operator_voidpt/), 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).

Because << has higher precedence than ?.

Fun exercise:

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

Take that, Coding Horror!!!

Your code is equivalent to:

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

It outputs 1 because, well, (a != 0) == true;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!