Correct comparison of signed type with unsigned type (and vice versa)

Xinok xinok at live.com
Thu Feb 20 12:52:22 PST 2014


The following statement prints false:

writeln(-1 < uint.max);

This came up in another topic recently. I think this is silly and
an unnecessary source of bugs (it's bitten me before and
presumably many others as well). I'm making a proposal to add an
extra check so that comparisons of signed with unsigned types is
always correct. Simply, if the signed type is negative, it is by
default less than the unsigned value. The compiler has all the
information it needs at compile time to add this check where
necessary. I demonstrate the problem and solution here:

http://dpaste.dzfl.pl/acd819d1a9ea

Others have suggested disallowing comparing a signed type with an
unsigned type. I think this is a better solution. Yes, it will
add a small bit of overhead, but I believe it's more important
for code to be correct than to be fast.

Any takers?


More information about the Digitalmars-d mailing list