|
-
Oct 25th, 2005, 04:30 PM
#1
Thread Starter
Lively Member
[RESOLVED] [C] Integer overflow
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.
-
Oct 26th, 2005, 03:25 AM
#2
Re: [C] Integer overflow
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
Last edited by wossname; Oct 26th, 2005 at 03:41 AM.
I don't live here any more.
-
Oct 27th, 2005, 06:21 PM
#3
Thread Starter
Lively Member
Re: [RESOLVED] [C] Integer overflow
ok, thanks. I did a google just after i posted this and found out the theory and all that to the overflows.
-
Oct 31st, 2005, 06:57 AM
#4
Re: [RESOLVED] [C] Integer overflow
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.
-
Oct 31st, 2005, 01:23 PM
#5
Fanatic Member
Re: [RESOLVED] [C] Integer overflow
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|