[clang] [clang] Do not diagnose float-equal for 0 and 1 (PR #207288)
Junior Rantila via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 7 05:43:09 PDT 2026
juniorrantila wrote:
I did some more digging and can't find the exact PDF I was looking for, but in MISRA 1998, rule 40 states:
Floating-point variables shall not be tested for exact equality or inequality.
**How the rule is checked**
The compiler will generate an error, indicating a violation of this rule, if == or != is
applied to a floating-point value. If a comparison is explicitly against the floating-point
constant 0.0, no error message is given.
In MISRA 2004 (Rule 13.3), they removed the comparison to zero exemption.
However, in MISRA 2012 and onward they removed the floating point comparison rule altogether, no longer explicitly disallowing floating point equality comparison,
instead it is indirectly disallowed by other rules. [MISRA C:2012 Rule 10.1](https://la.mathworks.com/help/bugfinder/ref/misrac2012rule10.1.html) allows comparisons to `0`, `INFINITY` and `-INFINITY`. They clarify this in (https://misra.org.uk/app/uploads/2022/12/MISRA-C-2012-AMD3.pdf)[MISRA C:2012 Amendment 3] (2.3.7 Amend Rule 10.1), they allow this because there is code that needs to guard against those specific values, for instance to catch division by zero.
Static analysis tools seem to commonly allow comparisons to `0` and `INFINITY` and comparisons where it can prove that the value does not drift, for instance:
```c
for (float v = 0.0f; v != 100.0f, v += 1.0f)
;
```
would be allowed on the grounds that the initializer and the value we increment by are both integer values, so the float will not drift. See [Polyspace](https://www.mathworks.com/help/bugfinder/ref/floatingpointcomparisonwithequalityoperators.html).
In my opinion, `0` and `INFINITY` should be allowed by default with this `-Wfloat-equal`, since you commonly want to guard against those values. Additionally, we could have a flag that restricts the use of `0`. As for other float values (other than `0` and `INFINITY`), maybe we should not allow them by default and provide a flag to allow exact float values, this way, people who intend to compare to the same bit pattern can still do so.
https://github.com/llvm/llvm-project/pull/207288
More information about the cfe-commits
mailing list