Integer promotion... what I'm missing? (It's monday...)
Daniel Keep
daniel.keep.lists at gmail.com
Mon Jun 19 02:24:19 PDT 2006
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
--
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d-learn
mailing list