Ok, im making a basic calculator that does operations with integers. The user enters a string like "1 + 2" and then displays the result. How do I check to make sure that there is no overflow? I have to use only ints, not long long ints or anything.
Printable View
Ok, im making a basic calculator that does operations with integers. The user enters a string like "1 + 2" and then displays the result. How do I check to make sure that there is no overflow? I have to use only ints, not long long ints or anything.
Check for a sign change.
Positives will wrap around to negative numbers and vice versa whenever there is an overflow.
If (sign before) != (sign after) then: overflow
ok, thanks. I did a google just after i posted this and found out the theory and all that to the overflows.
Halve both numbers, add them together, and check if the result exceeds half of the maximum value allowed. That way you can stay with ints, and it avoids the possible overflow if you not only wrap around to negatives but exceed the minimum negative number in doing so.
For both signed and unsigned integers: if the result is smaller than one of the input values, then an overflow has occurred as well. If you add a negative value, treat it as a subtraction of a positive value, see below.
Also, for subtractions: if the result is larger than the first input value, then an overflow has occurred, except if you're subtracting a negative number. In that case, treat it as an addition of a positive number, and see above. (It's not called underflow, if you might think that. That only occurs with floating point values near zero.)
By the way, if you use multiplication, then it isn't detected that easily. As far as I can tell, you can only test for overflow onbeforehand: determine the position of the largest bit set of both input values (it's actually a logarithm: 2log), and make sure that the sum of them isn't larger than the maximum limit of the specific integer type. In case one (or both) input value is negative, determine the position of the largest bit which is not set.
There's nothing to worry about with divisions, except that you must take in mind that you're performing integer divisions, and you must make sure that you don't divide by zero.