Boost logo

Ublas :

From: Ian McCulloch (ianmcc_at_[hidden])
Date: 2007-09-19 19:25:10


Hi Karl,

On Wed, 19 Sep 2007, Karl Meerbergen wrote:

> Most software for scientific programming uses int as size type. It takes
> time to adapt to this. Is there an advantage using unsigned int types?
> (I use std::size_t most of the time, unless when I link with external
> software) Do the advantages justify potential errors that (naive) users
> may make? For example, working with banded matrices is sometimes easier
> when indices can be negative.

IMHO, there is no advantage to using an unsigned int, and it is a shame
that the STL standardized on an unsigned size_type. Unsigned has a
positive range that is twice as big, but really, how often is that
needed? For anything other than arrays of char, the answer is never, and
personally I've never seen an array of char bigger than 2^31 anyway.

The rules for mixing signed and unsigned arithmetic in C/C++ are such a
trap that you want to avoid it, it almost never gives what you want, or
if it does it is an accident. eg, given declarations unsigned u=4; int
i=-5; int j = u+i; will give the right result on most hardware, but it is
actually unspecified because typeof(u+i) is unsigned with a value that is
out of the range of an int. The conversion from unsigned to signed is
then unspecified (or is it implementation defined? I'm not sure which
applies here), but it `accidentally' works on 2's compliment hardware.

I do tend to use unsigned for array indices where the termination
condition involves a comparison with a size_type. But this is only to
avoid gcc warnings on mixing signed/unsigned arithmetic. I used to have
these warnings turned off but on gcc, this warning is the mechanism used
by boost::mpl::print, so without the warning turned on mpl::print is
useless. And on reflection, the warnings are probably valid, although for
a simple loop it is annoying.

Cheers,
Ian