Is there any reason why arithmetic operation on shorts and bytes return int?

foobar foo at bar.com
Tue Dec 11 11:29:47 PST 2012


On Tuesday, 11 December 2012 at 16:09:14 UTC, Andrei Alexandrescu 
wrote:
> On 12/11/12 8:24 AM, d coder wrote:
>>
>>    No, it's a fix of a gotcha from C. The C code would just 
>> allow the
>>    assignment.
>>
>>
>> Yes Andrei.
>>
>> But it does not look clean if you have to write:
>>
>> byte a, b, c;
>> a = cast(byte) (b + c);
>>
>> Well I know the advantages (safety). But imagine having to 
>> write all
>> that when working with bytes and shorts. Makes it really 
>> difficult to
>> work with shorts and bytes in D.
>
> Value range propagation automatically avoids the need for a lot 
> of those casts. 
> http://www.drdobbs.com/tools/value-range-propagation/229300211
>
>> Would I be asking for too much if I ask
>> DMD to provide a compiler flag that makes it return bytes and 
>> shorts for
>> operations on them?
>
> That won't happen.
>
>
> Andrei

But than we have a bug in the value range propagation algorithm.
E.g in the original program:
void main()
{
  import std.stdio;
  ushort a = 0x55AA;
  ushort b = 0xAA55;
  writefln("%X", ~(a | b));
}

(a | b) will be in the range of ushort values and ~ of that also 
remains in the same value range. In other words, it makes no 
sense that boolean ops (and, or, xor, 1's compliment, 2's 
compliment) will require type promotion as they cannot exceed the 
original width of the values. This is unlike arithmetic which can 
require promotion.


More information about the Digitalmars-d mailing list