2011/12/14 Justin Lebar <
justin...@gmail.com>:
> derf has sagely advice, as usual:
>
> Don't use unsigned integers as loop indices. Signed overflow is
> undefined behavior, so the compiler can assume that your signed loop
> index doesn't overflow. But the compiler has to correctly handle
> unsigned overflow.
>
> Indeed, glandium sees better code for some loops with int than with
> unsigned int.
>
> I wonder if Benoit would see better performance if he used ssize_t
> instead of size_t in his matrix library.
I wholeheartedly agree, and my matrix library actually uses ptrdiff_t
instead of size_t for loop indices.
I only used size_t in the above discussion as I wanted to discuss only
one problem at a time (the sizeof) and the signed-vs-unsigned thing is
not 100% consensual everywhere. But since we seem to all agree that
signed is better than unsigned, great.
It's not just a matter of helping the compiler optimize. It's also
important to guard against a common programming mistage:
for(unsigned int stupid = max; stupid >= 0; stupid--) { boom; }
Note that AFAIK ssize_t is POSIX only while ptrdiff_t is available
everywhere, so I prefer the latter.
I would also add in the coding guidelines a general paragraph about
unsigned types. Here's my guiding rule: use signed types by default,
only use unsigned when:
1) you really really want that extra bit of large positive values, or
2) this is not going to be used in any +-/* arithmetic (e.g. bit-fields), or
3) you really want the compiler to be able to optimize x/2 into
x>>1 and you don't want to have to write x>>1 manually; or some other
similar optimization thing.
These are the only 3 reasons I know to use unsigned types.
Cheers,
Benoit