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:
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
- If the sum of two negative numbers yields a positive result, the sum has overflowed.
- Otherwise, the sum has not overflowed.
2 Answers 2
Rule #2 from
http://sandbox.mc.edu/~bennet/cs110/tc/orules.html
is incorrect
- 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
- If the sum of two negative numbers yields a non-negative result, the sum has overflowed.
As for Rule #1
- If the sum of two positive numbers yields a negative result, the sum has overflowed.
it's correct one
Comments
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
unchecked context. Otherwise I wouldn't get an overflown value but an OverflowException.