Integer Overflow in C++ Coding Interviews: The Complete Guide

June 18, 20267 min read
dsaalgorithmsinterview-prepdata-structures
Integer Overflow in C++ Coding Interviews: The Complete Guide
TL;DR
  • Signed integer overflow is undefined behavior in C++: the compiler may delete your overflow check entirely at -O2.
  • long long is the only portable 64-bit integer type; long is 32 bits on Windows and 32-bit Linux.
  • The binary search midpoint (left + right) / 2 overflows when both values are near INT_MAX; use left + (right - left) / 2.
  • Cast before multiplying: (long long)a * b is correct; (long long)(a * b) is too late.
  • Use 1e18 as your infinity constant for Dijkstra distance arrays; INT_MAX + weight wraps silently.
  • GCC/Clang's __int128 handles 128-bit intermediate products when long long overflows in modular exponentiation.

You write int mid = (left + right) / 2. The logic is correct. The test cases pass. Then your interviewer asks what happens when left and right are both near two billion.

Silence.

Not the thoughtful kind. The specific silence of someone realizing they have been writing a famous 20-year-old bug in front of a senior engineer who definitely knows about it.

C++ integer overflow is the category of bug that compiles clean, runs quietly, and hands you a wrong answer with no error message. In an interview, you have 45 minutes. You cannot afford to debug it after the fact. You need to not write it.


The long Type Is Lying to You

C++ guarantees minimum sizes, not exact sizes. int is at least 16 bits, but virtually every modern platform gives you 32. long is at least 32 bits. That last word matters: on Windows and 32-bit Linux, long stays at 32 bits. On 64-bit Linux and macOS, it grows to 64 bits. Your code compiles on one, breaks on the other.

The only portable 64-bit integer type in C++ is long long. It is guaranteed 64 bits on every conforming compiler. Use it whenever you need more than roughly two billion.

TypeBitsMaximum
int322,147,483,647
unsigned int324,294,967,295
long long649,223,372,036,854,775,807
unsigned long long6418,446,744,073,709,551,615

Two billion is 2 × 10^9. The int max is about 2.1 × 10^9. If your problem has n up to 10^5 and you are multiplying two values together, you are already outside int range.

Use numeric_limits from <limits> instead of the C macros:

#include <limits> int cap = std::numeric_limits<int>::max(); // 2147483647 long long big = std::numeric_limits<long long>::max(); // 9223372036854775807

Signed Overflow Is Undefined. The Compiler Will Use That Against You.

Unsigned overflow wraps modulo 2^N. UINT_MAX + 1 is zero, guaranteed, on every conforming compiler. You can reason about it.

Signed overflow is undefined behavior. Not "implementation-defined." Not "wraps around on x86, probably." The standard lets the compiler assume signed overflow never happens and optimize accordingly. That means the compiler is legally allowed to look at code like this:

// You write this to be safe if (x + 1 < x) { handle_overflow(); }

And delete it. Not skip it at runtime. Delete it at compile time. The compiler sees a signed addition that overflows, concludes the branch is unreachable (because undefined behavior cannot happen, by assumption), and removes your safety check entirely. This is not hypothetical. It happens in production, under -O2, silently.

If you write INT_MAX + 1 in an interview, that is undefined behavior. The result might look like INT_MIN on your machine. It might not. Either way, your interviewer already knows what it is.


Four C++ Integer Overflow Traps That Show Up in Every Interview

The Binary Search Midpoint

// Overflows when left and right are both near INT_MAX int mid = (left + right) / 2; // Correct: right - left cannot exceed the array size int mid = left + (right - left) / 2;

Jon Bentley's original binary search had this bug for over 20 years. The Java standard library shipped with it for nine. If you invoke the authority of a textbook while writing a binary search, it would be nice if the textbook had gotten the midpoint right.

C++20 also provides std::midpoint(left, right) from <numeric>, which is overflow-safe and rounds toward the left argument.

Multiplication Before the Cast

int a = 100000, b = 100000; long long wrong = a * b; // Overflows int first, then stores long long right_way = (long long)a * b; // Promotes both to long long first

The cast must happen before the arithmetic. By the time you assign to long long, the value has already wrapped. The destination type does not reach back in time and fix it.

1e9 Looks Like a Number. It Is a Double.

int limit = 1e9; // Compiles. 1e9 is a double literal assigned to int.

The value fits here, but mixing floating-point notation into integer arithmetic creates implicit conversions you did not intend. Write 1000000000 or 1'000'000'000 (C++14 digit separator). For a long long, write 1000000000LL. The e notation is for floats. Keep the types honest.

n × (n - 1) and Similar Products

int n = 100000; long long wrong = n * (n - 1); // int multiplication, overflows long long right = (long long)n * (n - 1); // Correct

Any quadratic expression on a variable that can reach 10^4 or above needs a cast. The interviewer will notice, and "I forgot to cast" is not a great explanation when the entire interview has been about overflow.


What to Reach for When long long Is Not Enough

Some problems require intermediate products that exceed 9.2 × 10^18. Modular exponentiation with large moduli is the classic case: (a * b) % mod can produce a product over 10^36 before the mod.

GCC and Clang both support __int128, which gives you 128 bits and a range up to roughly 1.7 × 10^38. MSVC does not, but most interview judges and competitive programming environments use GCC or Clang. You are basically making up a type, and the compiler plays along.

__int128 x = (__int128)a * b; long long result = (long long)(x % mod);

No printf format specifier, no std::cout, no std::numeric_limits. For interview use, you usually only need it for intermediate arithmetic and cast back before returning.

void print128(__int128 x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) print128(x / 10); putchar('0' + (int)(x % 10)); }

Your INT_MAX Initializer Is a Trap

This comes up in Dijkstra and other graph problems where you initialize a distance array.

// Fragile: dist[v] + weight overflows if dist[v] is INT_MAX vector<int> dist(n, INT_MAX); // Use long long and a large constant const long long INF = 1e18; vector<long long> dist(n, INF);

INF + weight must not wrap. INT_MAX + 1 wraps quietly back to INT_MIN, and your shortest path becomes -2147483647. 1e18 + 1 does not wrap. The choice of 1e18 rather than LLONG_MAX is deliberate: it leaves a margin so you never accidentally overflow during relaxation.

(1e18 is a double literal, but it converts cleanly to long long. Alternatively, write 1'000'000'000'000'000'000LL. Either works.)


Quick Reference

// Types: only trust long long for 64-bit portability int // 32 bits, max ~2.1e9 long long // 64 bits, max ~9.2e18 __int128 // 128 bits, GCC/Clang only, max ~1.7e38 // Safe midpoint int mid = left + (right - left) / 2; int mid = std::midpoint(left, right); // C++20, from <numeric> // Cast before multiply long long result = (long long)a * b; // Integer literals (not float) 1'000'000'000 // int, C++14 digit separator 1000000000LL // long long // Infinity constants const int INF = 0x3f3f3f3f; // ~1e9, safe for int DP const long long INF = 1e18; // safe for long long DP // Numeric limits std::numeric_limits<int>::max() // 2147483647 std::numeric_limits<long long>::max() // 9223372036854775807 // Overflow-checking builtins (GCC/Clang) bool overflowed = __builtin_add_overflow(a, b, &result); bool overflowed = __builtin_mul_overflow(a, b, &result);

If you want to catch these bugs in real time, under interview pressure, the best practice is saying your type choices out loud as you code. SpaceComplexity runs voice-based DSA mock interviews with rubric-based feedback, so you build the habit of narrating type decisions before they become silent bugs.


Further Reading


See also: int32 vs int64: The Overflow Bug Every Coding Interview Tests | Integer Overflow in C++ Interviews: The Silent Bug | C++ Coding Interview Gotchas: The Traps That Cost You the Offer | Two's Complement: The Bit Trick Behind Every Negative Integer