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?
int.MinValueis -2,147,483,648 and-1-xis +2,147,483,647 but-xis +2,147,483,648 (which doesn't fit into an int). So really you're asking why-x-1overflows but-1-xdoesn't. Well, since operations go left to right, it should be more evident. Negating x causes an overflow, but sub(-1, x) doesn't.sub.ovf(0, x), and second one tosub.ovf(sub.ovf(0, x), 1). In both expressions,sub.ovf(0, x)appears which causes the overflow. For the last one, it's simplysub.ovf(-1, x)which produces a results within Int32 bounds, hence no overflow.