0

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?

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67
Koda
  • 1,709
  • 3
  • 14
  • 15
  • 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). – harold Sep 13 '12 at 17:40
  • 1
    The "nasty expression" is `(((x + y) ^ x) & ((x + y) ^ y)) < 0`, by the way. – harold Sep 13 '12 at 17:57

1 Answers1

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.

Phillip Schmidt
  • 8,805
  • 3
  • 43
  • 67
  • This is the same answer as the "possible duplicate" vote to close instead. – JonH Sep 13 '12 at 17:34
  • Is checked the best way to check this since it throws an exception. Is checking if the result is negative not a better way? – Koda Sep 13 '12 at 17:35
  • @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. – Phillip Schmidt Sep 13 '12 at 17:37
  • Thanks, but when would checking for negative not work? – Koda Sep 13 '12 at 17:41
  • @Alvin if non-overflowing cases can also result in a negative result. – harold Sep 13 '12 at 17:41
  • Yes, but for the case where you are only adding 2 positive numbers together, it should work right? – Koda Sep 13 '12 at 17:43
  • @Alvin yeah, if they're integers – Phillip Schmidt Sep 13 '12 at 17:44
  • @harold come on, now. int.MaxValue + int.MaxValue = -2. (When I posted that, I was thinking -1). Either way, you're saying that -2 + 2, or -1 + 2 is an overflow? – Phillip Schmidt Sep 13 '12 at 17:57