implicit ubyte casting

Don nospam at
Fri Oct 2 07:08:50 PDT 2009

Jeremie Pelletier wrote:
> Don wrote:
>> Saaa wrote:
>>> Jeremie Pelletier wrote
>>>> Saaa wrote:
>>>>> I think is very bug-prone, isn't it obvious iub should be -5?
>>>>> ubyte ub = 5;
>>>>> int iub = -ub; // iub now is 251
>>>>> What is the reasoning to do it this way?
>>>> Minus toggles the most significant bit, be it on a signed or 
>>>> unsigned type. When converting it to an int, the byte being signed 
>>>> or unsigned does make a difference: when unsigned the number is 
>>>> copied as is, when signed the most significant bit (bit 7) is 
>>>> shifted to the most significant bit of the int (bit 31).
>>>> Its therefore pretty standard logic, no warning is given since the 
>>>> entire ubyte range fits within an int
>>>> Jeremie
>>> Thanks, but it is not that I do not know how it occurs more that
>>> I should have asked whether people use this kind of logic.
>>> For me it resulted in annoying bug like this:
>>> for(int i = nloop;i<10;i++);//ubyte nloop is created quite a few 
>>> lines above.
>> This has been discussed before, and it really should be an error.
>> It's reasonable to implicitly cast between integral types of different 
>> size, and also signed<->unsigned, but performing both within the same 
>> expression is almost always a bug. It should not be possible without 
>> an explicit cast.
> I know VC++ shouts a warning everytime signed and unsigned integrals are 
> mixed, maybe that's the road D should take too.

We can do *much* better than that.
About two releases ago D2 got integer range tracking, so you can do 
things like:
long a = someCrazyFunction();
ubyte b = (a & 7) | 0x60; // No worries! This is perfectly fine!
ubyte c = a;  // Error, might overflow.

It just needs to be extended a bit more. It's far from finished.

More information about the Digitalmars-d-learn mailing list