NaN to Bool conversion: True or False?

后端 未结 1 1061
半阙折子戏
半阙折子戏 2021-02-12 15:47

What part of the C++ spec, or the IEEE float spec, states that a NaN value should convert to true as opposed to false?

If I look at the C++ standard section

相关标签:
1条回答
  • 2021-02-12 16:24

    In both C and C++, the behaviour is undefined when converting NAN to an integer type (other than bool):

    C99 6.3.1.4/1: When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

    C++11 4.9/1: A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]

    In both languages, converting NAN to bool (or _Bool) gives true (or 1):

    C99 6.3.1.2/1: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

    C++11 4.12/1: A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.

    NAN is not a zero value, and doesn't compare equal to zero.

    0 讨论(0)
提交回复
热议问题