On Mon, 11 Nov 2024 21:14:43 +0000 (UTC)
Joseph Myers via Gcc <gcc@gcc.gnu.org> wrote:

> On Sat, 9 Nov 2024, Sad Clouds via Gcc wrote:
> 
> > Even though there is nothing unsafe here and comparison to floating
> > point 0.0 value is well defined.
> 
> The point of the warning is that *if you are writing code that thinks
> of floating-point values as being approximations to real numbers*
> then such comparisons are suspect.  If you are writing code that
> thinks of floating-point values as exactly represented members of
> their type ... then you should not use that warning option for such
> code.

You could be right.  But IMO -Wfloat-equal is an example of solving the
wrong problem.  

I do not think warnings from the C compiler should extend to valid
numerical constructs.  It is the programmer's job to understand how
floating point works.  If he does not, there's precious little the
compiler can do for him.  

Here's a bogus function that compiles without diagnostic using -Wall: 

int f( double g ) {
  double gs[10];

  for( double *pg = gs; pg < gs + 12; pg++ ) {
    *pg = 2 * g;
    g = *pg;
  }

  return g;
}

We have UB, a fencepost error on an array of known size using a bound of
known size.  The returned value might or might not be representable as
an int, depending on the initial value of g. I'm not sure what happens
if INT_MAX < g. 

Everyone reading this sees the problems, but the compiler does not.  If
10 and 12 are named constants, some of the obviousness goes away.  So
does the integer conversion if the return type uses a typedef.  

But we do have a warning about comparing g as equal to something, in
case *that* helps.  

Granted, "it's the programmer's job" extends to everything.  You should
get your fprintf format strings correct, say.  And no one is forced to
use -Wfloat-equal.  

There are at least 2^53 exact values that a double can be initialized
to and compared against.  This diagnostic might help the occasional
1st-year programmer learn something about C.  But it's too
simple-minded to be much use beyond that.  

--jkl



Reply via email to