Search code examples
c++comparisonfloating-point

Is floating-point == ever OK?


Just today I came across third-party software we're using and in their sample code there was something along these lines:

// Defined in somewhere.h
static const double BAR = 3.14;

// Code elsewhere.cpp
void foo(double d)
{
    if (d == BAR)
        ...
}

I'm aware of the problem with floating-points and their representation, but it made me wonder if there are cases where float == float would be fine? I'm not asking for when it could work, but when it makes sense and works.

Also, what about a call like foo(BAR)? Will this always compare equal as they both use the same static const BAR?


Solution

  • There are two ways to answer this question:

    1. Are there cases where float == float gives the correct result?
    2. Are there cases where float == float is acceptable coding?

    The answer to (1) is: Yes, sometimes. But it's going to be fragile, which leads to the answer to (2): No. Don't do that. You're begging for bizarre bugs in the future.

    As for a call of the form foo(BAR): In that particular case the comparison will return true, but when you are writing foo you don't know (and shouldn't depend on) how it is called. For example, calling foo(BAR) will be fine but foo(BAR * 2.0 / 2.0) (or even maybe foo(BAR * 1.0) depending on how much the compiler optimises things away) will break. You shouldn't be relying on the caller not performing any arithmetic!

    Long story short, even though a == b will work in some cases you really shouldn't rely on it. Even if you can guarantee the calling semantics today maybe you won't be able to guarantee them next week so save yourself some pain and don't use ==.

    To my mind, float == float is never* OK because it's pretty much unmaintainable.

    *For small values of never.