Do Not Compare NaN
ID |
go.do_not_compare_nan |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious-comparison |
Description
Reports == / != comparisons where one operand is a call to math.NaN(). By the IEEE 754
specification, NaN is not equal to anything — including itself — so x == math.NaN() is always
false and x != math.NaN() is always true.
Rationale
x == math.NaN() never holds, regardless of x. The branch the comparison guards never runs,
the bug hides, and the NaN check the developer intended is missing. The correct test is
math.IsNaN(x).
func check(x float64) bool {
if x == math.NaN() { // FLAW — always false
return true
}
return math.IsNaN(x) // OK — the correct NaN test
}