Why C# checked
keyword does not treat -1 - int.MinValue
as overflow?
int x = int.MinValue;
int y;
checked {
// Overflow. 2^31 cannot be represented in signed integer.
try { y = -x; } catch (OverflowException) { Console.WriteLine ("Overflow 1"); }
// Overflow. Though the final result (2^31-1) fit in an integer, the intermediate value does not.
try { y = -x-1; } catch (OverflowException) { Console.WriteLine ("Overflow 2"); }
// No overflow. Please explain.
try { y = -1-x; } catch (OverflowException) { Console.WriteLine ("Overflow 3"); }
}
Output:
Overflow 1
Overflow 2
Is this a bug in C# overflow checking, or something related to processor architecture?
In example 1 and 2, you have unary operator -
in front of x
. It has highest precedence, so the negating operation is first and throws.
In example 3, you have binary operator -
in front of x
. The result of the subtraction is not overflowing, it's 2147483647 which fits int32.
It's just math - that Int.MinSize is a negative number and you're subtracting it. Let's use 32 bit numbers.
Int32.MinValue= -2147483648
Int32.MaxValue= 2147483,647
-1 - (-2147483648) = 2147483,647
You end up precisely with the value of Int.MaxValue, so there is no overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With