Preventing implicit conversion

Dominikus Dittes Scherkl via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 5 14:15:44 PST 2015


On Thursday, 5 November 2015 at 13:23:34 UTC, Adam D. Ruppe wrote:
> On Thursday, 5 November 2015 at 10:07:30 UTC, Dominikus Dittes 
> Scherkl wrote:

>> ubyte b = 1u;
>> auto c = b + 1u;
>>
>> I expect the 1u to be of type ubyte - and also c.
>
> This won't work because of the one-expression rule. In the 
> second line, it doesn't know for sure what b is, it just knows 
> it is somewhere between 0 and 255. So it assumes the worst, 
> that it is 255, and you add one, giving 256... which doesn't 
> fit in a byte.
That would be fine - but c is not ushort (which the worst-case 
256 would fit in), not even uint, but int! A signed type! Just 
because of the crazy C interger propagation rules!
And, ok, one needs to accept that auto may not do exactly what I 
wish for, but if I give an exact type that is likely to fit (and 
has to if all operands are of the same type), I expect it to work 
without extra casts:

ubyte d = b + 1u; // doesn't compile
ubyte d = b + (ubyte)1; // works - and overflows to 0 if b is 255


More information about the Digitalmars-d-learn mailing list