Always false float comparisons

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Mon May 9 13:25:10 PDT 2016


Am Mon, 9 May 2016 02:10:19 -0700
schrieb Walter Bright <newshound2 at digitalmars.com>:

> Don Clugston pointed out in his DConf 2016 talk that:
> 
>      float f = 1.30;
>      assert(f == 1.30);
> 
> will always be false since 1.30 is not representable as a float. However,
> 
>      float f = 1.30;
>      assert(f == cast(float)1.30);
> 
> will be true.
> 
> So, should the compiler emit a warning for the former case?

I'd say yes, but exclude the case where it can be statically
verified, that the comparison can yield true, because the
constant can be losslessly converted to the type of 'f'.

By example, don't warn for these:
f == 1.0, f == -0.5, f == 3.625, f == 2UL^^60

But do warn for:
f == 1.30, f == 2UL^^60+1

As an extension of the existing "comparison is always
false/true" check it could read "Comparison is always false:
literal 1.30 is not representable as 'float'".

There is a whole bunch in this warning category:
  byte b;
  if (b == 1000) {}
"Comparison is always false: literal 1000 is not representable
as 'byte'"

-- 
Marco



More information about the Digitalmars-d mailing list