This seems like what could be a common cause of bugs
Marco Leise
Marco.Leise at gmx.de
Sun Aug 14 18:25:25 PDT 2011
Am 09.07.2011, 00:45 Uhr, schrieb Andrej Mitrovic
<andrej.mitrovich at gmail.com>:
> This is just an observation, not a question or anything.
>
> void main()
> {
> enum width = 100;
> double step = 1 / width;
>
> writeln(step); // 0
> }
>
> I've just had this bug in my code. I forgot to make either width or 1
> a floating-point type. IOW, I didn't do this:
>
> void main()
> {
> enum width = 100.0;
> double step = 1 / width; // or .1
>
> writeln(step); // now 0.01
> }
>
> This seems like a very easy mistake to make. But I know the compiler
> is probably powerless to do anything about it. It has an expression
> resulting in an int at the RHS, and it can easily cast this to a
> double since there's no obvious loss of precision when casting
> int->double.
>
> Where's those lint tools for D.. :/
That's why Pascal uses another set of operators for integer divisions,
namely 'div' and 'mod', so you can never get into that situation. The
above code would have worked and in case step was an integer, the compiler
would have complained about not using 'div'. I doubt that we will see
these in D - at the end of the day code that is both valid C and valid D
must do the same thing, but I never had problems with 'div' and 'mod' and
it seems like a good solution.
More information about the Digitalmars-d-learn
mailing list