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:
It won't be true if x
is NaN
, since comparisons on NaN
are always false (yes, even NaN == NaN
). For all other cases (normal values, subnormal values, infinities, zeros) this assertion will be true.
The advice for avoiding ==
for floats applies to calculations due to floating point numbers being unable to express many results exactly when used in arithmetic expressions. Assignment is not a calculation and there's no reason that assignment would yield a different value than the original.
Extended-precision evaluation should be a non-issue if the standard is followed. From
inherited from C [5.2.4.2.2.8] (emphasis mine):
Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type.
However, as the comments have pointed out, some cases with certain compilers, build-options, and targets could make this paradoxically false.