Integer promotion issue

Steven Schveighoffer schveiguy at gmail.com
Sat Jan 25 23:58:00 UTC 2020


On 1/25/20 6:46 PM, 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?

Not really. You can cast yourself, write your own type that does it, or 
use masking to have the compiler accept the result (i.e. (a + b) & 0xff).

I'd recommend your own type, as it will look a lot cleaner.

-Steve


More information about the Digitalmars-d mailing list