Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Int32.MinValue - 1 return Int32.MaxValue?

Tags:

c#

clr

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?

like image 491
Peter Kiers Avatar asked Dec 05 '22 21:12

Peter Kiers


2 Answers

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.

like image 88
Oded Avatar answered Dec 16 '22 07:12

Oded


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

like image 34
Andreas Eriksson Avatar answered Dec 16 '22 08:12

Andreas Eriksson