Integer promotion... what I'm missing? (It's monday...)

Tony ignorethis at nowhere.com
Mon Jun 19 03:11:32 PDT 2006


"Daniel Keep" <daniel.keep.lists at gmail.com> wrote in message 
news:e75qg4$2bt$1 at digitaldaemon.com...
>
>
> Paolo Invernizzi wrote:
>> Hi all,
>>
>> What I'm missing?
>>
>>     uint a = 16;
>>     int b = -1;
>>     assert( b < a ); // this fails! I was expecting that -1 < 16
>>
>> Thanks
>>
>> ---
>> Paolo
>
> If you read http://digitalmars.com/d/type.html, you will find the rules
> for integer promotion under arithmetic operations (which I assume also
> includes comparisons).
>
> Note point 5.4 under "Usual Arithmetic Conversions":
>
> 5.4. The signed type is converted to the unsigned type.
>
> Hence, b is being converted to a uint.  cast(uint)(-1) = ~0 = uint.max,
> hence why b is not less than a.
>
> If you're going to compare a signed and unsigned type directly, it's
> best to explicitly cast them to a common type, or strange things like
> this could happen :)  Either convert a to an int (and watch for
> overflow), or convert them both to a long (so you don't have problems
> with overflow).
>
> -- Daniel

I believe it is a mistake to have an operation like this occur when it is 
both mathematically incorrect and unintuitive.  It feels like something that 
is destined to be a Bug Breeder.

I would prefer that any type promotions (and any implicit operations for 
that matter) should guarantee not to introduce any data corruption.  In this 
case, promote both numbers to a third type which can hold all possible 
values from both.

If the user wishes to override that by making explicit conversions, at least 
this will be visible in the code.

Tony
Melbourne, Australia






More information about the Digitalmars-d-learn mailing list