Comparison With NaN Using == or !=
ID |
java.test_nan_equality |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
CWE:597, reliability |
Description
Reports equality comparisons (== or !=) against Double.NaN or Float.NaN. By IEEE 754 specification, NaN is not equal to any value including itself, so x == Double.NaN is always false and x != Double.NaN is always true.
Rationale
This is a common and insidious bug. The comparison compiles without warnings but always yields the same result regardless of the value of x. The code path guarded by the comparison is either dead code (for ==) or always taken (for !=).
// Bad - ALWAYS false, even when x is NaN
if (x == Double.NaN) {
handleNaN(); // unreachable
}