 The Limitations of Integers in C++ - dummies

The int variable type is the C++ version of an integer. int variables suffer the same limitations as their counting-number integer equivalents in math do.

## Integer round-off

Lopping off 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 — an equation for calculating the average is

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

Because all three values are integers, the sum is assumed to be an integer. Given the values 1, 2, and 2, the sum is 5. Divide that by 3, and you get 12⁄3, or 1.666. C++ uses slightly different rules: Given that all three variables nValue1, nValue2, and nValue3 are integers, the sum is also assumed to be an integer.

The result of the division of one integer by another integer is also an integer. Thus, the resulting value of nAverage is the unreasonable but logical value of 1.

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

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

Plugging in the same 1, 2, and 2 values, the resulting value of nAverage is 0 (talk about unreasonable). To see how this can occur, consider that 1⁄3 truncates to 0, 2⁄3 truncates to 0, and 2⁄3 truncates to 0. The sum of 0, 0, and 0 is 0. You can see that integer truncation can be completely unacceptable.

## Limited range

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

Two billion is a very large number: plenty big enough for most uses. But it’s not large enough for some applications, including computer technology. In fact, your computer probably executes faster than 2 gigahertz, depending on how old your computer is. (Giga is the prefix meaning billion.)

A single strand of communications fiber — the kind that’s been strung back and forth from one end of the country to the other — can handle way more than 2 billion bits per second.