Quiz Entry - updated: 2026.07.07
Your C program multiplies positive numbers but suddenly produces negative results. What's happening and how do you diagnose it?
Integer overflow: the result passed the type's maximum and wrapped around into the negative range.
The fix usually starts with the types — an int tops out near 2.1 billion, so a calculation that should grow past that silently wraps. Widen the type (or check the operands) before the operation, and watch for intermediate results overflowing even when the final answer would fit.
Diagnosis steps:
- Check the data types involved (
intmax is ~2.1 billion) - Add debug output before the operation to see values
- Consider if intermediate results overflow, not just final
Solutions:
- Use larger types (
long longinstead ofint) - Check for overflow before operations
- Use compiler flags like
-ftrapv(GCC) to catch overflows
Warning signs:
- Positive × Positive = Negative
- Large positive + Large positive = Negative
- Calculations that "should" grow suddenly shrink
Go deeper:
What Every C Programmer Should Know About Undefined Behavior (LLVM blog) — signed overflow is undefined behavior, so the compiler may assume it never happens and optimize surprisingly.
Integer overflow (Wikipedia) — how exceeding INT_MAX flips the sign bit and yields a negative value.