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

Daniel Kozak via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 19 14:32:57 PST 2016


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.

immutable ubyte a = 0;
ubyte b = 0;
ubyte c = a + b;

or

ubyte a = 0;
ubyte c = a + 0;

or

immutable ubyte a = 1;
immutable ubyte b = 5;
ubyte c = a + b;

works ok

but

immutable ubyte a = 1;
ubyte b = 0;
ubyte c = a + b;

can't works because b could be 255 and 255 + 1 does not fit to ubyte


> On principal I'm not casting to fix this. I don't care if my 
> computer needs to do math on a 4 byte basis, I'm not writing 
> assembly. I'm really hoping this is a bug because trying to use 
> any type other than ints is going to make for some really ugly 
> code otherwise...
> 
> Can I prevent the initial implicit casts?
> 
> 
> On the topic of complaining about casting... array lengths as 
> ulongs is painful... any chance of an array[].lengthi being a 
> thing?
array.length is not ulong is it size_t and I do not see any problem
with that, can you be more specific.


More information about the Digitalmars-d-learn mailing list