I chose to be as explicit as possible while programming. That is, if I intend to use a variable whose value is always positive, then unsigned
is used. Many here mention "hard to spot bugs" but few give examples. Consider the following advocate example for using unsigned
, unlike most posts here:
enum num_things {
THINGA = 0,
THINGB,
THINGC,
NUM_THINGS
};
int unsafe_function(int thing_ID){
if(thing_ID >= NUM_THINGS)
return -1;
...
}
int safe_function(unsigned int thing_ID){
if(thing_ID >= NUM_THINGS)
return -1;
...
}
int other_safe_function(int thing_ID){
if((thing_ID >=0 ) && (thing_ID >= NUM_THINGS))
return -1;
...
}
/* Error not caught */
unsafe_function(-1);
/* Error is caught */
safe_function((unsigned int)-1);
In the above example, what happens if a negative value is passed in as thing_ID
? In the first case, you'll find that the negative value is not greater than or equal to NUM_THINGS
, and so the function will continue executing.
In the second case, you'll actually catch this at run-time because the signedness of thing_ID
forces the conditional to execute an unsigned comparison.
Of course, you could do something like other_safe_function
, but this seems more of a kludge to use signed integers rather than being more explicit and using unsigned to begin with.
int
iflength
may be negative. If you useunsigned int
, thenlength
gets converted tounsigned int
too. -1 becomes something like 4294967295, and bad things happen.length
is much smaller thanINT_MAX
then it is equivalent to useint
andunsigned int
. I go with the one that is less typing :)length
is ofint
type why do you need to useunsigned
?i
goes to the max value (which is very unlikely ifi
is an array index andi
is 32-bits or bigger), it doesn't really matter if you use signed or unsigned. The only reasonunsigned
exists is if you actually need that most significant bit to extend your positive range by another factor of 2 but not more.