I know that using ==
to check equality of floating-point variables is not a good way. But I just want to know that with the following statements:
Yes, in all cases (disregarding NaNs and x87 issues), this will be true.
If you do a memcmp
on them you will be able test for equality while being able to compare NaNs and sNaNs. This will also require the compiler to take the address of the variable which will coerce the value into a 32-bit float
instead of an 80-bit one. This will eliminate the x87 issues. The second assertion here is intended to fail to show that ==
will not compare NaNs as true:
#include
#include
#include
int main(void)
{
float x = std::nan("");
float y = x;
assert(!std::memcmp(&y, &x, sizeof(float)));
assert(y == x);
return 0;
}
Note that if the NaNs have a different internal representation (i.e. differing mantissa), the memcmp
will not compare true.