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 4.12 Boolean Conversions it says:
A zero value, null pointer value, or null member pointer value is
converted to false; any other value is converted to true.
Now IEEE floats say that NaN compares false to any other value. So whether NaN is true or false depends on how you do your comparision (below). Thus I presume there must be an explicit mention.
value == 0 ? false : true
value != 0 ? true : false
Now, what about conversion to an integer. The short program below shows that a variable NAN converted to an integer results in the minimum integer, whereas a constant gets converted to 0 (using GCC). This seems odd.
#include <iostream>
#include <cmath>
void write( double r, int i, bool b )
{
std::cout << r << " == " << i << " == " << (b ? "True" : "False") << std::endl;
}
int main()
{
double value = NAN;
write( value, value, value );
write( NAN, NAN, NAN );
}
Output:
nan == -2147483648 == True
nan == 0 == True
The conversion of a NaN to zero but bool conversion as True seems troubling. I also not that something like MatLab will convert a NaN to 0 using a function like int16.
So, what are the specifics of the relevant standards that state how NaN converts to boolean and integer values?
I’m tagging C as well, since while it may not define the boolean conversion, it probably defines an integral conversion and use in a conditional and I suspect C++ will follow the same rules
In both C and C++, the behaviour is undefined when converting
NANto an integer type (other thanbool):In both languages, converting
NANtobool(or_Bool) givestrue(or1):NANis not a zero value, and doesn’t compare equal to zero.