Integer Limits and long long

An int is stored in a fixed amount of memory, so it cannot hold every whole number. There is a largest int and a smallest one. The <climits> library gives them names: INT_MAX and INT_MIN.

#include <iostream>
#include <climits>
using namespace std;

int main() {
    cout << INT_MAX << "\n";
    cout << INT_MIN << "\n";
    return 0;
}

Output:

2147483647
-2147483648

So an int holds numbers up to about 2 billion. That sounds like a lot, but many real numbers are bigger, like the population of the world or the sum of many large values.

Going past the limit

What happens when you add 1 to the largest int?

int big = INT_MAX;
big = big + 1;
cout << big << "\n";

Output:

-2147483648

When we ran this, the number jumped from the largest int to the smallest one. Going past the limit is called overflow. The program gave no error and no warning.

This result is not a rule. For int, the C++ rules say overflow is undefined behavior, which means C++ does not say what happens. Another compiler, or the same one with different settings, can give a different result. So never write code that depends on what overflow does. Make sure it never happens.

long long holds bigger numbers

When a number can go above about 2 billion, use the type long long. It works like int, but its limit, LLONG_MAX, is much bigger:

long long views = 2500000000;
cout << views << "\n";
cout << LLONG_MAX << "\n";

Output:

2500000000
9223372036854775807

That is about 9 followed by 18 zeros, which is enough for almost every program.

The int * int trap

Here the result goes into a long long, but it still comes out wrong:

int a = 50000;
int b = 50000;
long long product = a * b;
cout << product << "\n";

Output:

-1794967296

The right answer is 2,500,000,000. The problem is the order. C++ first works out a * b. Both values are int, so the multiplication is done as int, and it overflows. Only then is the broken result stored in product. A long long on the left does not help.

The fix is the same idea as in the Type Conversion lesson: convert one value before the multiplication.

long long correct = static_cast<long long>(a) * b;
cout << correct << "\n";

Output:

2500000000

Now one side is a long long, so C++ does the whole multiplication as long long. You can also declare a and b as long long from the start.

This trap is very common in coding problems and interviews. When the values in a problem can be large, check every sum and product, and use long long for anything that can pass 2 billion.

In the exercise, multiply two numbers whose product does not fit in an int.