Last Updated: February 25, 2016
·
1.761K
· dionysios

Two Common Pitfalls Using Unsigned Int

Usually it is a good idea to use an unsigned instead of a regular int for representing a natural number. It makes the program more efficient, doubles the range of the variable, and makes the programmer's intention more clear.
However, there are two common pitfalls with this approach:

If there is an expression involving both signed and unsigned integers, the signed integers get promoted to unsigned:

unsigned int x = 1;
int y = -2;
(x + y > 0) ? puts("WRONG ANSWER") : puts("CORRECT ANSWER");  //Output: WRONG ANSWER

Loops where the control variable is an unsigned integer can easily become infinite loops.

for(unsigned z = 5; z >= 0; z--){doSomething(z);}  // Infinite Loop

The above problem is sometimes present even if we do not declare any unsigned variables in which case it is harder to spot. In the example below, the size of the string is unsigned, which makes the expression on the right negative which is translated to a large positive value.

const int lengthLimit = 10;
const std::string example = "EXAMPLE";
int index = 0;
while(++index < example.size() - lengthLimit){doSomething();}   //A LOT of iterations

The easiest remedy is to move variables from one side of the comparison to the other such that we always have additions when there is at least one unsigned variable in the expression:

const int lengthLimit = 10;
const std::string example = "EXAMPLE";
int index = 0;
while(++index +  lengthLimit < example.size()){doSomething();}   //No iterations