Can't add ubytes together to make a ubyte... bug or feature?

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 19 16:15:06 PST 2016


On Tue, 19 Jan 2016 23:32:57 +0100, Daniel Kozak wrote:

> Soviet Friend píše v Út 19. 01. 2016 v 22:12 +0000:
>> I just attempted to add one ubyte to another and store the result in a
>> ubyte but apparently ubytes get converted to ints when being added...
>> and converting what becomes an int becomes impossible to store in a
>> ubyte without an explicit cast...
>> 
>> ubyte a, b;
>> ubyte c = a + b; // Error: cannot implicitly convert expression
>> (cast(int)a + cast(int)b) of type int to ubyte
>> 
>> 
> Problem is that compiler does not know that a + b would fit in ubyte.
> For example if a would be 200 and b would be 100 it would not fit in
> ubyte. But if compiler can verify it will fit it makes cast implicit.

This is true for all integer types. The reason this isn't in effect for 
other types is that most values are small (eg array lengths), and most 
integer types can hold the sum of two small values. But there are plenty 
of small values where a [u]byte can't hold their sum.


More information about the Digitalmars-d-learn mailing list