Reputation: 602
When I execute the following code, I have (for me) some unexpected behaviour.
int i = Int32.MinValue;
i--;
if (i == Int32.MaxValue)
{
Console.WriteLine("i == Int32.MaxValue");
}
i++;
if (i == Int32.MinValue)
{
Console.WriteLine("i == Int32.MinValue");
}
Why doesn't the -1 on Int32.MinValue throw an Exception?
Upvotes: 5
Views: 2009
Reputation: 9027
From MSDN:
When integer overflow occurs, what happens depends on the execution context, which can be checked or unchecked. In a checked context, an OverflowException is thrown. In an unchecked context, the most significant bits of the result are discarded and execution continues. Thus, C# gives you the choice of handling or ignoring overflow.
Upvotes: 5
Reputation: 799110
C#, like C, doesn't actually do overflow/underflow checks unless explicitly written/told to do so. As such, it has no problem subtracting 1 from 100...000
and getting 011...111
.
Upvotes: 2