MISRA C++:2008 Rule 6-2-2
Floating-point expressions shall not be directly or indirectly tested for equality or inequality
Description
Rule Definition
Floating-point expressions shall not be directly or indirectly tested for equality or inequality.1
Rationale
Due to the inherent rounding errors of floating-point numbers, there is no way to reliably compare floating-point numbers for equality. This includes both direct and indirect tests of equivalency. Comparisons of floating-point numbers can result in a false outcome when you expect equivalence. This behavior is unpredictable and can vary between implementations.
Avoid using floating-point numbers for equivalence comparisons. Alternatively, write a library that implements your comparison operations. Take into account the magnitude of numbers to compare as well as floating-point granularity during creation of this library.
Polyspace Implementation
The rule checker detects the use of ==
or !=
with
floating-point variables or expressions. Additionally, the rule checker detects indirect
tests of equality or inequality of floating-point variables. For
example:
float x, y = 0.0; if ((x < y) || (x > y)) //Noncompliant { //... }
Troubleshooting
If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Statements |
Category: Required |
Version History
Introduced in R2013b
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.