Main Content

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.

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

expand all

This code contains different examples of floating-point number comparisons. Polyspace reports a violation for each of these floating-point tests of equality or inequality.

  • x == y, due to the use of ==

  • x == 0.0f, due to the use of !=

  • ((x <= y) && (x >= y)), due to an indirect comparison of equality

  • ((x < y) || (x > y)), due to an indirect comparison of inequality

#include <cmath>
#include <limits>

void main()
{
    float x, y = 0.0;
    if (x == y)          //Noncompliant
    {
        //...
    }
    if (x != 0.0f)       //Noncompliant
    {
        //...
    }
    if ((x <= y) && (x >= y))         //Noncompliant
    {
        //...
    }
    if ((x < y) || (x > y))           //Noncompliant
    {
        //...
    }
}

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2013b