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?
There are two ways to answer this question:
float == floatgives the correct result?float == floatis 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 writingfooyou don’t know (and shouldn’t depend on) how it is called. For example, callingfoo(BAR)will be fine butfoo(BAR * 2.0 / 2.0)(or even maybefoo(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 == bwill 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 == floatis never* OK because it’s pretty much unmaintainable.*For small values of never.