Why int.Max+ int.Max = -2

.net, c#

Solution

Let's play this with 4-bit integers. The max signed value is `0x7`.

0x7 + 0x7 = 14 = 0xE

`0xE` is one less than the maximum unsigned value `0xF`. The maximum unsigned value interpreted as signed is always `-1` because adding `1` to it overflows to `0` (just like `(-1) + 1 = 0`).

So you have `(-1) - 1 = -2`.

Further note that addition behaves the same way for signed and unsigned integers on a bit-level. That's why I was allowed to jump between signed and unsigned in the above statements.

Here's something different:

int.MaxValue + int.MaxValue = -2
(int.MaxValue + 1) + (int.MaxValue + 1) - 2 = -2
int.MinValue + int.MinValue - 2 = -2
0 - 2 = -2

So why is `int.MinValue + int.MinValue = 0`? `int.MinValue` only has the most significant bit set. Doubling `int.MinValue` therefore just shifts the MSB bit one to the left and out of the integer. The result is `0`. Like this:

int.MinValue + int.MinValue = 0
int.MinValue * 2 = 0
int.MinValue << 1 = 0 //int.MinValue is 0x80000000, shift out the left bit

You can use LINQPad to conveniently play with these expressions. You need to wrap them in `unchecked` so that the C# compiler stops warning you of all the overflows happening here.

As you can see it is possible to intuitively grasp Two's Complement Arithmetic if you play around a little.

How to deal with integer overflow?

- Either use a type that can hold the result: `(long)int.MaxValue + (long)int.MaxValue`.

- Or, at least be notified of this probable bug: `checked(int.MaxValue + int.MaxValue)`.

Problem

``` int a = int.MaxValue; int b = int.MaxValue; int c = a + b; ``` Why `c=-2`always? I have checked in loop also. Its seems garbage value but why `-2` only ?

Original source