Do negative numbers return false in C/C++?

后端 未结 5 1355
傲寒
傲寒 2020-12-04 13:25

When evaluating integers as booleans in C/C++, are negative numbers true or false? Are they always true/false regardless of compilers?

5条回答
  •  鱼传尺愫
    2020-12-04 13:30

    All non-zero values will be converted to true, and zero values to false. With negative numbers being non-zero, they are converted to true.

    Quoting from the C++11 standard (emphasis mine):

    4.12 Boolean conversions [conv.bool]

    1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.


    Are they always true/false regardless of compilers?

    You will only get the above guarantee when your compiler is standards-compliant, or at least, complies with this specific part of the standard. In practice, all compilers have this standard behavior, so there isn't much to worry about.

提交回复
热议问题