[LC++]int versus unsigned int

Davide Bolcioni 9odb6x3rfr001 at sneakemail.com
Fri Sep 28 06:52:20 UTC 2001


Mark Phillips mark at austrics.com.au [mltuxcpp/linux-cpp list] wrote:

> 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."


I was bitten by this very strategy in the past and would

advise against it. Declare f(unsigned int x), call f(-1) and
have fun tracking the bug.


> 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.


This in my opinion will be the least of your worries.

 
> 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.


This was true when all we could play with was C. I make a point
of using an exception for exceptional cases (e.g. failure during IO)
and use assert() for logic errors (preconditions and postconditions),
both help immensely. If you use -1, you have to test for -1 ... all
over. Inside a function, I use a Fallible<> template or even a
boolean. On a larger scale, no invalid values should hang around
ever.


> 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!


As others pointed out, you're not. About the only advantage I can see
is with overloading, like the following:

class C
{
public:
   ...
   void f(unsigned int x) { ... normal case ... }
   void f(int x) { assert(x >= 0); f(static_cast<unsigned int>(x)); }
   ...

}


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


Occasionally, but size_t covers most such cases already; if I need
more integers than int, I try with long first. On some platforms,
this is a disappointment - I know.

 
> 3. Unsigned arithmetic is often slightly faster than signed.


Why ? The only circumstance I could think of is with CPUs such as
PowerPC not using condition register update for unsigned operations,
but I doubt it. I would really appreciate being enlightened on such
matters, in any case.

Davide Bolcioni
-- 
There is no place like /home.




More information about the tuxCPProgramming mailing list