Promotion rules ... why no float?

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 6 01:53:36 PDT 2016


On Tuesday, September 06, 2016 07:26:37 Andrea Fontana via Digitalmars-d 
wrote:
> On Tuesday, 6 September 2016 at 07:04:24 UTC, Sai wrote:
> > Consider this:
> >
> > import std.stdio;
> > void main()
> > {
> >
> >     byte a = 6, b = 7;
> >     auto c = a + b;
> >     auto d = a / b;
> >     writefln("%s, %s", typeof(c).stringof, c);
> >     writefln("%s, %s", typeof(d).stringof, d);
> >
> > }
> >
> > Output :
> > int, 13
> > int, 0
> >
> > I really wish d gets promoted to a float. Besides C
> > compatibility, any reason why d got promoted only to int even
> > at the risk of serious bugs and loss of precision?
> >
> > I know I could have typed "auto a = 6.0" instead, but still it
> > feels like an half-baked promotion rules.
>
> Integer division and modulo are not bugs.

Indeed. There are a lot of situations where they are exactly what you want.
Floating point adds imprecision to calculations that you often want to
avoid. Also, if I understand correctly, floating point operations are more
expensive that the corresponding integer operations. So, it would be very
bad if dividing integers resulted in a floating point value by default. And
if you _do_ want a floating point value, then you can cast one of the
operands to the floating point type you want, and you'll get floating point
arithmetic. Personally, I find that I rarely need floating point values at
all.

Another thing to take into account is that you don't normally want stuff
like arithmetic operations to do type conversion. We already have enough
confusion about byte and short being converted to int when you do arithmetic
on them. Having other types suddenly start changing depending on the
operations involved would just make things worse.

- Jonathan M Davis



More information about the Digitalmars-d mailing list