Comparison Nan
ID |
csharp.comparison_nan |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
CSharp |
Tags |
float, reliability |
Description
Reports comparisons in which one operand is the IEEE-754 NaN constant
(double.NaN, float.NaN, Double.NaN or Single.NaN). NaN is the only value
that compares unequal to itself and unordered to every other value, so every such
comparison always returns false regardless of the other operand.
Rationale
x == double.NaN is always false, even when x itself is NaN, because the
IEEE-754 standard defines all comparisons against NaN to return false (or
true for !=, which means x != double.NaN is always true). The intent is
almost always to ask "is this value NaN", which has its own predicate.
double x = ComputeRatio();
if (x == double.NaN) { /* never reached */ } // FLAW — always false
if (x != double.NaN) { /* always */ } // FLAW — always true
if (x < double.NaN) { /* never reached */ } // FLAW — NaN is unordered
if (double.IsNaN(x)) { /* ... */ } // OK
Remediation
Use double.IsNaN(x) / float.IsNaN(x) to detect NaN. To test for non-NaN, use
!double.IsNaN(x).