By Stephen R. Davis

The int variable type is the C++ version of an integer. As such, int variables suffer the same limitations as their counting integer equivalents in mathematics do.

Integer round-off

It isn’t that an integer expression can’t result in a fractional value. It’s just that an int has no way of storing the fractional piece. The processor lops off the part to the right of the decimal point before storing the result. (This lopping off of the fractional part of a number is called truncation.)

Consider the problem of calculating the average of three numbers. Given three int variables — nValue1, nValue2, and nValue3 — their average is given by the following expression:

int nAverage = (nValue1 + nValue2 + nValue3)/3;

Suppose that nValue1 equals 1, nValue2 equals 2, and nValue3 equals 2 — the sum of this expression is 5. This means that the average is 5 / 3 or either 1-2/3 or 1.666, depending upon your personal preference. But that’s not using integer math.

Because all three variables are integers, the sum is assumed to be an integer as well. And because 3 is also an integer, you guessed it, the entire expression is taken to be an integer. Thus, given the same values of 1, 2, and 2, C++ will calculate the unreasonable-but-logical result of 1 for the value of nAverage.

The problem is much worse in the following mathematically equivalent formulation:

int nAverage = nValue1/3 + nValue2/3 + nValue3/3;

Plugging in the same values of 1, 2, and 2, the resulting value of nAverage is now 0 (talk about logical-but-unreasonable, there it is). To see how this can occur, consider that 1/2 truncates to 0, 2/3 truncates to 0, and 2/3 truncates to 0. The sum of 0, 0, and 0 is (surprise!) 0.

You can see that there are times when integer truncation is completely unacceptable.

Limited range

A second problem with the int variable type is its limited range. A normal int can store a maximum value of 2,147,483,647 and a minimum value of −2,147,483,648 — that’s roughly from positive 2 billion to negative 2 billion — for a total range of 4 billion.

That’s on a modern PC, Mac, or other common processor. If you have a much older machine, the int may not be nearly so expansive in its range.

Two billion is a very large number — plenty big enough for most applications. That’s why the int is useful. But it’s not large enough for some applications, including computer technology. In fact, your computer probably executes faster than 2 GHz (gigahertz) (2 GHz is two billion cycles per second).

A single strand of fiber cable (the kind that’s strung back and forth from one side of the country to the other) can carry way more than 2 billion bits per second.