Peter Kiers
Peter Kiers

Reputation: 602

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

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

Answers (4)

Prince John Wesley
Prince John Wesley

Reputation: 63698

int is a two's complement binary number.

Upvotes: 2

Andreas Eriksson
Andreas Eriksson

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.

Link to MSDN

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

Oded
Oded

Reputation: 499142

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.

Upvotes: 8

Related Questions