I know there are a lot of questions on here about why float equality comparison is usually a bad idea. I understand float representation issues, rounding issues, silent promotion of floats to doubles, the dangers in relying upon arithmetic at the bit level, etc. But it seems to me that this should be fine, and no questions I found seem to cover this:
static const float MARKER = -500.0f; // some value well outside the range of valid values
std::vector<float> some_floats = {MARKER, 0.5f, 100.0f, 9.5f, MARKER, 0.f};
for (size_t i = 0; i< some_floats.size(); ++i) {
if (some_floats[i] == MARKER) {
std::cout << i << std::endl;
} else {
// do some math
}
}
The output is as expected:
0
4
If I have -Wfloat-equal
enabled (in gcc, but similar in other compilers), it will flag the comparison line as dangerous:
comparing floating point with == or != is unsafe
. And pretty much all the answers on here say not to use == or !=, period. But I don't see why it's a problem here. I'm only setting the constant once and re-using it everywhere else it's used, and there is never any manipulation of that constant (e.g. arithmetic). Am I missing something? What about 0.0f
, even if not set as a constant?