Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (-1 - int.MinValue) does not cause integer overflow?

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?

like image 497
Jatin Sanghvi Avatar asked Oct 19 '25 01:10

Jatin Sanghvi


2 Answers

In example 1 and 2, you have unary operator - in front of x. It has highest precedence, so the negating operation is first and throws.

In example 3, you have binary operator - in front of x. The result of the subtraction is not overflowing, it's 2147483647 which fits int32.

like image 121
Ivan Petrov Avatar answered Oct 20 '25 16:10

Ivan Petrov


It's just math - that Int.MinSize is a negative number and you're subtracting it. Let's use 32 bit numbers.

Int32.MinValue= -2147483648
Int32.MaxValue= 2147483,647

-1 - (-2147483648) = 2147483,647

You end up precisely with the value of Int.MaxValue, so there is no overflow.

like image 33
Egor Avatar answered Oct 20 '25 17:10

Egor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!