6

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?

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

2 Answers2

2

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

5 Expressions

4 If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined. [ Note: most existing implementations of C++ ignore integer overflows. Treatment of division by zero, forming a remainder using a zero divisor, and all floating point exceptions vary among machines, and is usually adjustable by a library function. —end note ]

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>.

Community
  • 1
  • 1
dirkgently
  • 108,024
  • 16
  • 131
  • 187
1

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 https://stackoverflow.com/a/199413/445525

Community
  • 1
  • 1
James Youngman
  • 3,623
  • 2
  • 19
  • 21