[previous] MISRA-C:2004  Rule  13.3:  (Required) [next] Floating-point expressions shall not be tested for equality or inequality.
The inherent nature of floating-point types is such that comparisons of equality will often not evaluate to true even when they are expected to. In addition the behaviour of such a comparison cannot be predicted before execution, and may well vary from one implementation to another. For example the result of the test in the following code is unpredictable:

float32_t x, y;
/* some calculations here          */
if ( x == y )     /* not compliant */
{ /* ... */ }
if ( x == 0.0f )  /* not compliant */
{ /* ... */ }

An indirect test is equally problematic and is also forbidden by this rule, for example:

if ( ( x <= y ) && ( x >= y ) )
{ /* ... */ }

The recommended method for achieving deterministic floating-point comparisons is to write a library that implements the comparison operations. The library should take into account the floating-point granularity (FLT_EPSILON) and the magnitude of the numbers being compared.


QAC messages that encompass this guideline:

3341 Comparing floating point expressions for equality (with '==' or '!=').



(c) The Motor Industry Research Association, 2004
QA C Source Code Analyser 8.1.2
MISRA-C:2004 Compliance Module 3.2
© 2013 Programming Research
www.programmingresearch.com
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index Contents