Signed-unsigned comparisons in Phobos

Don nospam at nospam.com
Fri Aug 12 12:37:20 PDT 2011


Jonathan M Davis wrote:
> On Friday, August 12, 2011 12:39:01 Don wrote:
>> kennytm wrote:
>>> Don <nospam at nospam.com> wrote:
>>>> I've had a look at a dozen or so of these, and they were all real. I
>>>> didn't see any which require a cast to "make the compiler shut up".
>>>> That's pretty impressive. In C++ I find that such messages are nearly
>>>> always false positives.
>>>>
>>>> The one case where it's a bit annoying is this:
>>>>
>>>> int [] x = new int[6]; // or x = some array literal.
>>>> for (int i = 0; i < x.length; ++i) {...}
>>>>
>>>> Here is a suggestion for how we could eliminate such false positives.
>>>> http://d.puremagic.com/issues/show_bug.cgi?id=6478
>>> Doesn't this require flow analysis?
>> Yes. See the bug report.
>>
>>> And the type of index 'i' should be 'size_t' anyway.
>> Why? It will only ever be in the range 0..6.
> 
> Sure. it works in this case, but in the general case it's good practice to use 
> size_t for indices, because that's the actual type of the index, so it won't 
> have signedness or range problems. 

But it will have signedness problems if you try to use it any expression 
that involves a subtraction. Basically, unsigned types are poisonous, 
and for modern systems, size_t should have been an signed type. It's 
very unfortunate.

Unfortunately, it's a practice that many
> people don't seem to follow (in both C/C++ and D), since it's so natural to 
> use int (or auto in D), but I'd definitely argue that programmers should 
> normally be using size_t for indices.

You actually have fewer bugs if you use int, _provided_ that you can 
guarantee that the length can't be greater than int.max.
(Of course, you can't generally guarantee that; hence your 
recommendation is a good one).



More information about the Digitalmars-d mailing list