[LC++]int versus unsigned int

Mark Phillips mark at austrics.com.au
Wed Sep 26 16:15:06 UTC 2001


Hi,

I am having to decide whether to define things as int or as
unsigned int.  To date I have been using the strategy:

	"Unless it has to be int, declare it as unsigned int."

But I'm not sure if this is the right strategy.  Some problems
with it seem to be:

1. If I ever need to use it in "int" calculations, I have to do
casts everywhere, ie static_cast<int>(i), which is unsightly and
time consuming.

2. Even if mostly all you want is an unsigned int, having the
capability of using negative numbers is useful on occasions.  For
example, you can use -1 to flag that a calcuation resulted in an
error.  And it's easy to test for such an error, because you just
ask if "i<0", which presumably is a very efficient test.  You can
also use a -1 to indicate that a non-negative variable has not been 
assigned its value yet.  None of these options are possible with
an unsigned int.

3. Using unsigned ints rather than ints seems to be a little
unconventional most of the time (for example with for loops),
so it makes your code less readable (but why is it unconventional?).

The advantages, as I see it, of using unsigned int are:

1. You are more strongly typing things, which presumably leads to
better compiler error checking --- if you have a variable that isn't
supposed to be negative, you tell the compiler that!

2. You can store more non-negative numbers (double the amount).

3. Unsigned arithmetic is often slightly faster than signed.




So as you see, there are pros and cons.  Has anyone any further 
light to shed on the subject?

Thanks,

Mark.



More information about the tuxCPProgramming mailing list