Annoyance with new integer promotion deprecations
Luís Marques
luis at luismarques.eu
Tue Feb 6 22:38:36 UTC 2018
On Monday, 5 February 2018 at 23:56:51 UTC, Adam D. Ruppe wrote:
> 1) Given:
> byte a, b;
> byte c = a + b;
>
> The cast seems a bit silly: you are already explicitly using
> `byte` everywhere, so your intention is pretty clear: you only
> want to use the bytes and are ok with the rest of it being
> discarded. Therefore, I find the cast to be an unnecessary
> addition.
Yeah, it's annoying. For my MSP430 work (16-bit, lots of shorts
and bytes) I created a generic type which works around this, so
you would do:
byte c = a.nx + b;
where .nx means "non-extending" and converts/wraps the
(u)byte/(u)short in my special type. The arithmetic operations
are infectious, so you only need to apply it to one of the
operands (and you can preserve it across statements by using
"auto" instead of "byte"). Because D doesn't have automatic type
conversions for the function calls, the function signatures still
take the standard types, and you add .nx where needed in the
body. Because the higher-order bits are discarded after each
operation, the optimizer easily optimizes away the multi-word
operations (as least in all of the cases I bothered checking...).
Given the impasse between preserving C compatibility and the
problems that that compatibility brings, I think the ideal
situation would be to have some kind of mode, in the same way
that extern(C) is a "mode":
// option 1
pragma(nointpromos): // opt-in
byte c = a + b;
// option 2
pragma(cintpromos): // opt-out of D's new, non-compatible, rules
byte c = cast(byte) (a + b);
Unfortunately, I'm not holding my breath for something like this.
At least D is flexible enough that my .nx solution works! That's
saying a lot about the language.
More information about the Digitalmars-d
mailing list