Length comparison

xs0 xs0 at xs0.com
Tue Dec 5 01:43:34 PST 2006


Bill Baxter wrote:
> This bit me just now:
> 
>     if (-1 < somearray.length) {
>     }
> 
> Ouch.  Took me a while to figure out that that bit of code was the problem.
> 
> Is there some way to make these kind of bugs less likely or easier to find?

It should be made illegal :) In particular:
- comparing a negative constant with an unsigned variable
- comparing a too large constant with a signed variable (like 
3_000_000_000 and something of type int)
- setting an unsigned var to a negative constant (uint a = -1)

For other cases, comparing signed with unsigned should produce a warning 
and, more importantly, work properly:

int a;
uint b;

a < b  should be  a < 0 || cast(uint)a < b
a > b  should be  a > 0 && cast(uint)a > b
etc.etc.

I'm quite sure someone will say that's much slower so shouldn't be done, 
but:
- you can do it properly and only compare variables of the same type in 
the first place
- you can trivially make it fast again by casting, with the positive 
side effect of explicitly stating whether you want to use signed or 
unsigned comparison
- I doubt signed/unsigned comparisons are common enough to even make any 
noticeable speed difference

Thoughts? :)


xs0



More information about the Digitalmars-d mailing list