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?
Beware that signed int overflow is undefined behaviour in C and C++, and thus you have to detect it without actually causing it. For signed int overflow before addition, see Detecting signed overflow in C/C++.
There are two ways to get around this: Cast the numbers to a bigger integer type, then do the addition there, and check if the result is in the right range. Do the addition normally, then check the result (e.g. if (a+23<23) overflow).
The rules for detecting overflow in a two's complement sum are simple: If the sum of two positive numbers yields a negative result, the sum has overflowed. If the sum of two negative numbers yields a positive result, the sum has overflowed. Otherwise, the sum has not overflowed.
An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With