Take the 2-minute tour ×

Possible Duplicate:
Best way to detect integer overflow in C/C++

Oftentimes when I've coded something in C++ using large numbers I can't tell when overflow is occurring, even if I am using something like a long long or other 64-bit data type. Is there an effective way to detect when overflow is occurring than witnessing erroneous values?

share|improve this question

marked as duplicate by casperOne Jun 6 '12 at 12:32


Instead of using raw integer values, you could use objects with overloaded arithmetic operators that throw exceptions when overflow occurs. –  jamesdlin Jun 2 '12 at 19:54
what is the operation that you are doing on the numbers? –  Baget Jun 2 '12 at 19:55
@Baget could be anything. addition, subtraction, multiplication, exponent, so on. depends on the program. –  John Smith Jun 2 '12 at 19:56
In Assembler you could access the overflow bit of your CPU, but that would of course be platform dependent. –  bitmask Jun 2 '12 at 19:58

2 Answers 2

up vote 2 down vote accepted

There may not be much that you would get from standard C++:

5 Expressions


Your best bet is to probably use the standard fixed width integer types defined in <cstdint> such as uint32_t.

Take a look at the <cerrno> header too for error codes such as EOVERFLOW. There are then the overflow_error/underflow_error classes from <stdexcept>.

share|improve this answer
EOVERFLOW can be set by library functions, but it not set by arithmetic operations. –  James Youngman Jun 2 '12 at 20:27

Actually you can't even reliably detect overflow after the fact because overflow in signed integer operations results in undefined behaviour. If the compiler can see that a code path is only reached in the event of an overflow, it's allowed to optimise it out entirely (since in the undefined behaviour case it can do anything at all). Unsigned types are different in that they have defined overflow characteristics (they perform modulus arithmetic).

So the only way to detect overflow with signed types is to make the appropriate check beforehand, which is quite expensive. It is almost always much more efficient to design things such that an invariant of your algorithm ensure that there cannot be an overflow.

As for resources on detecting the possible overflow before it happens, see http://stackoverflow.com/a/199413/445525

share|improve this answer
