Hello, On Tue, 12 Nov 2024, Sad Clouds via Gcc wrote:
> > I don't think this has anything to do with whether one operand of the > > comparison is a constant. It's still the case when comparing with 0.0 > > that it's OK if your algorithm is designed such that the other operand > > is exact, and questionable if it is an approximation. > > Division by 0.0 is somewhat undefined, so should be avoided. That's what Joseph is alluding to. If you think of float as approximated reals, then yes, division by zero is undefined (not somewhat undefined!). When thinking about them for what they are (a precisely defined set with operations), then division by zero isn't undefined, it's perfectly defined to result in either NaN, Inf or -Inf. > One way of checking it is with the equality operator. So whether one of > the operands is exact or approximation is irrelevant, since we may only > be interested in preventing division by 0.0. Other values for the divisor will also produce Inf. If your goal was to avoid getting Inf, then checking for equality with zero _won't_ do: % cat x.c #include <math.h> #include <stdio.h> int main(void) { double divisor = 0x1p-52; double dividend = 0x1p1000; double result; if (divisor == 0.0) result = 42; // or whatever else result = dividend / divisor; printf ("%a %a\n", dividend, result); return 0; } % ./a.out 0x1p+1000 inf > So having -Wfloat-equal is desirable for catching other cases, but the > assumption of "if (divisor == 0.0) else ..." always being unsafe is a > bit pedantic. As this very discussion shows the warning seems to be quite worthwhile actually. As Joseph says, if your programming/mental model uses IEEE floats as real approximations: use the warning and don't check for (non)equality (normally range checks would be in order); if you're using them as IEEE floats, don't use the warning. And indeed, 0.0 isn't special in any way. There are many poles of many functions. If we were to exempt 0.0 from being warned about, then we would need to exempt all other constants C in 'x == C' as well, after all x could (the compiler doesn't know in general) be used in '1 / (x - C)'. Ciao, Michael.