Integer promotion issue

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Feb 6 04:06:17 UTC 2020


n Saturday, February 1, 2020 5:50:21 AM MST Shachar Shemesh via Digitalmars-
d wrote:
> On 26/01/2020 01:46, Evan wrote:
> > I am writing an 8 bit emulator that uses a lot of small numbers and
> > running into a problem where the compiler will automatically promote
> > smaller operands up to an int which causes the result of math
> > calculations to not fit into smaller types.
> >
> > //compiled with dmd 2.090.0
> > void main()
> > {
> >     ubyte a = 0x01;
> >     ubyte b = 0x01;
> >     ubyte c = a + b; //Error: cannot implicitly convert expression
> > cast(int)a + cast(int)b of type int to ubyte
> >     writeln(c);
> > }
> >
> > Is there a way to stop the compiler from up casting automatically? or
> > have it down cast it back once it's done?
>
> It was a recurring pet-peeve for me while working with D, and for pretty
> much the same reason as you (for me it was writing the RAID algorithm
> for Weka.io).
>
> I have since decided to write my own programming language, and,
> predictably, this was a problem I decided to tackle.
>
> I am posting this here in the hope that someone will be able to steal
> any good ideas I have. I am working on it, but I do so alone, and in my
> spare time (such that there is). I would much rather have good ideas be
> used than be given credit for them, but see them go unused.
>
> So if there is anything you think is worth stealing, please do. I don't
> think it is possible, as Practical's integer promotion rules are _very_
> different, and I don't see retrofitting them as plausible, but on the
> off chance I'm wrong:
>
> https://github.com/Practical/practical-sa/wiki/Implicit-casts

So, basically, narrowing conversions are stricter in that converting between
signed and unsigned types is treated as a narrowing conversion when it isn't
guaranteed that the target type can hold the original value, and integer
types smaller than int don't get changed to int when doing arinthmetic. It
seems like a better approach to me, though I don't know how easy it would be
to change D to function that way at this point even if we wanted to. Either
way, for a language starting from scratch, I'm inclined to think that it's a
more sensible approach than what we have in D.

- Jonathan M Davis





More information about the Digitalmars-d mailing list