4

When adding two positive Int32 values with a theoretical result greater than Int32.MaxValue can I count on the overflown value always being negative?

I mean to do this as a way to check for overflow without using a checked context and exception handling (like proposed here: http://sandbox.mc.edu/~bennet/cs110/tc/orules.html ), but is this behaviour garantueed?

From what I've read so far is signed integer overflow in C# defined behaviour (Is C#/.NET signed integer overflow behavior defined?) (in contrast to C/C++) and Int32 is two-complement so I would be thankful for someone with better understanding of this subject than me to verify this.

Update
Quote from link 1:

The rules for detecting overflow in a two's complement sum are simple:

  1. If the sum of two positive numbers yields a negative result, the sum has overflowed.
  2. If the sum of two negative numbers yields a positive result, the sum has overflowed.
  3. Otherwise, the sum has not overflowed.
0

2 Answers 2

4

Rule #2 from

http://sandbox.mc.edu/~bennet/cs110/tc/orules.html

is incorrect

  1. If the sum of two negative numbers yields a positive result, the sum has overflowed.

Counter example:

  int a = int.MinValue;
  int b = int.MinValue;

  unchecked {
    // 0
    Console.Write(a + b);
  }

However, the rule can be simply amended

  1. If the sum of two negative numbers yields a non-negative result, the sum has overflowed.

As for Rule #1

  1. If the sum of two positive numbers yields a negative result, the sum has overflowed.

it's correct one

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

Comments

1

No, you cannot.

You already talk about checked context, where you know that overflow causes an exception to be thrown. However, your seems to assume that the lack of a checked keyword indicates you're in unchecked context. That isn't necessarily the case. The default context when neither checked nor unchecked is specified is configurable, can be different in multiple projects that share the same source files, and can even be different between different configurations of the same project.

If you want integer overflow to wrap, be explicit, use the unchecked keyword.

2 Comments

I know. While it might be worth pointing out to others, I think the way I worded the question implies that I mean to use this in a unchecked context. Otherwise I wouldn't get an overflown value but an OverflowException.
@ArgusMagnus The way you worded the question implies to me that you mean to use this in the default implicit unchecked context, which is risky. The point of my answer is to make it an explicit unchecked context instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.