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?

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

EOVERFLOW can be set by library functions, but it not set by arithmetic operations.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.