[LC++]int versus unsigned int

Carlo Wood carlo at alinoe.com
Thu Sep 27 00:45:07 UTC 2001

On Wed, Sep 26, 2001 at 03:49:30PM +0930, Mark Phillips wrote:
> I am having to decide whether to define things as int or as
> unsigned int.
> So as you see, there are pros and cons.  Has anyone any further 
> light to shed on the subject?

Hi Mark,

first of all - I don't think that unsigned int calculations are
faster - it depends on conversions the compiler does that is
(larger assembly code); if you code the right way then it is
not faster.  For most operations the cpu doesn't care if it
is signed or not, that only affects comparision operations
and setting flags - all of which take the same number of
clock cycles.

Secondly, the argument that you can store double the ammount
is dangerous: you don't want to rely on that.  You should
consider an 'int' as exactly that: an integer, in the mathematical

-infinity ... -1, 0, 1, ... +infinity

The 'unsigned int' looks like:

... 4294967293, 4294967294, 4294967295, 0, 1, ... +infinity 

which isn't more safe in any way imho.

( unsigned int i = 0;
  does NOT give a warning).

A better strategy is therefore:

"Whenever an enum can be used (no mathematics are involved and the size of the
   int is unimportant (otherwise use uint16_t or something), use it.
 When a (small) integer is used (mathematical, or as counter), use an 'int'.
 When a size is needed (sizeof()) use size_t.
 When a bit mask is needed, use uint32_t.
 When the size of the integer is important (because it is part of a file
   format for instance), then use int32_t, int16_t, uint32_t etc.
 Use 'int' in all other cases."

Carlo Wood <carlo at alinoe.com>

More information about the tuxCPProgramming mailing list