Can we drop casts from float to bool?
bearophile
bearophileHUGS at lycos.com
Mon Mar 22 15:17:08 PDT 2010
Don:
> This conversion seems to be confusing, bug prone, and not useful. Can we
> just get rid if it?
So let me understand better the situation.
FP can be: various kinds of NaN, +0.0, -0.0, +infinite, -infinite, and normal numbers.
The language designers have to decide what to do for those various values in an instruction like if(x).
At the moment in D NaNs are true, +0.0 and -0.0 are false, and the other values are true.
Considering NaN as true looks like an arbitrary decision, but in general NaN means not a value, so it's not zero nor different from zero. So probably if(NaN) has to be a runtime error. I think that's what happens when NaNs are set as signalling.
Your solution is to forbid implicit and explicit casts of floating points to boolean values, because the choice of the true/false values is arbitrary, and because I think you are saying that packing normal values and NaNs as true is not meaningful in real programs.
Disabling conversions from FP to bools seems like able to break generic code. If I have a function template that can accept an int or FP and contains an if(x) it can't compile if the type of x is a FP. This can be solved writing if(x==0) that works with both ints and FPs (and it's true for +0.0 and -0.0). In D some people have proposed to change the semantics of the "is" operator, to make it more useful and tidy, so if you want to know if x is a NaN you can then write if(x is nan).
Writing if(x==0) is probably a little more explicit anyway, and Pascal/Java programmers are able to survive with it.
In conclusion I don't know if your idea can be a little bad for generic code, but overall I don't think it can hurt my code.
Bye,
bearophile
More information about the Digitalmars-d
mailing list