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?
Because of the underflow the values wrap around.
You need to use a checked
section if you want overflows/underflows to throw.
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
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.
Link to MSDN
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