1

What is the best way to check for integer overflow if I am adding 2 positive numbers together in c# if overflow isn't a condition that should cause an exception?

Can i just check if the result is negative then it is an overflow?

2
  • 1
    Yes, you can. But only because the two numbers you're adding are non-negative. Otherwise it either takes a nasty expression (see Hackers Delight) or an exception from checked (only makes sense if overflow is an exceptional and bad event - not for standard checking). Commented Sep 13, 2012 at 17:40
  • 1
    The "nasty expression" is (((x + y) ^ x) & ((x + y) ^ y)) < 0, by the way. Commented Sep 13, 2012 at 17:57

1 Answer 1

1

If overflow is OK, you could check for negative, but that wouldn't account for large enough overflows. If it overflows enough to become positive again, checking for negative obviously wouldn't work.

But for two positive integers, checking for negative will work fine.

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

8 Comments

This is the same answer as the "possible duplicate" vote to close instead.
Is checked the best way to check this since it throws an exception. Is checking if the result is negative not a better way?
@Alvin depends on the situation. If an overflow is bad, which it usually is, this is the best way to go. If not, maybe checking for negative. Checking for negative doesn't work for multiple (an even number of) overflows, though.
Thanks, but when would checking for negative not work?
@Alvin if non-overflowing cases can also result in a negative result.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.