C/C++ use of int or unsigned int C/C++ use of int or unsigned int c c

C/C++ use of int or unsigned int


Using unsigned can introduce programming errors that are hard to spot, and it's usually better to use signed int just to avoid them. One example would be when you decide to iterate backwards rather than forwards and write this:

for (unsigned i = 5; i >= 0; i--) {    printf("%d\n", i);}

Another would be if you do some math inside the loop:

for (unsigned i = 0; i < 10; i++) {    for (unsigned j = 0; j < 10; j++) {        if (i - j >= 4) printf("%d %d\n", i, j);    }}

Using unsigned introduces the potential for these sorts of bugs, and there's not really any upside.


It's generally laziness or lack of understanding.

I aways use unsigned int when the value should not be negative. That also serves the documentation purpose of specifying what the correct values should be.

IMHO, the assertion that it is safer to use "int" than "unsigned int" is simply wrong and a bad programming practice.

If you have used Ada or Pascal you'd be accustomed to using the even safer practice of specifying specific ranges for values (e.g., an integer that can only be 1, 2, 3, 4, 5).


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.