C/C++ use of int or unsigned int

developerbmw picture developerbmw · Mar 23, 2014 · Viewed 21.7k times · Source

In a lot of code examples, source code, libraries etc. I see the use of int when as far as I can see, an unsigned int would make much more sense.

One place I see this a lot is in for loops. See below example:

for(int i = 0; i < length; i++)
{
    // Do Stuff
}

Why on earth would you use an int rather than an unsigned int? Is it just laziness - people can't be bothered with typing unsigned?

Answer

Paul Hankin picture Paul Hankin · Mar 23, 2014

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.