[ACCEPTED]-Why int.MaxValue - int.MinValue = -1?-c#

Accepted answer
Score: 54

int.MaxValue - int.MinValue = a value which int cannot hold. Thus, the 13 number wraps around back to -1.

It is like 12 2147483647-(-2147483648) = 4294967295 which 11 is not an int

Int32.MinValue Field

The value of this constant 10 is -2,147,483,648; that is, hexadecimal 0x80000000.

And 9 Int32.MaxValue Field

The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.

From 8 MSDN

When integer overflow occurs, what happens 7 depends on the execution context, which 6 can be checked or unchecked. In a checked 5 context, an OverflowException is thrown. In 4 an unchecked context, the most significant 3 bits of the result are discarded and execution 2 continues. Thus, C# gives you the choice 1 of handling or ignoring overflow.

Score: 15

This is because of compile-time overflow 8 checking of your code. The line

Console.WriteLine(int.MaxValue - int.MinValue);

would not 7 actually error at runtime, it would simple 6 write "-1", but due to overflow checking 5 you get the compile error "The operation 4 overflows at compile time in checked mode".

To 3 get around the compile-time overflow checking 2 in this case you can do:

         unchecked
        {
            Console.WriteLine(int.MaxValue - int.MinValue);                
        }

Which will run fine 1 and output "-1"

Score: 2

The default project-level setting that controls 12 this is set to "unchecked" by default. You 11 can turn on overflow checking by going to 10 the project properties, Build tab, Advanced 9 button. The popup allows you to turn on 8 overflow checking. The .NET Fiddle tool 7 that you link to seems to perform some additional 6 static analysis that is preventing you from 5 seeing the true out-of-the-box runtime behavior. (The 4 error for your first code snippet above 3 is "The operation overflows at compile time 2 in checked mode." You aren't seeing a runtime 1 error.)

Score: 2

I think it goes even further than overflows.

if 6 i look at this

 Int64 max = Int32.MaxValue;
 Console.WriteLine(max.ToString("X16")); // 000000007FFFFFFF
 Int64 min = Int32.MinValue;
 Console.WriteLine(min.ToString("X")); //FFFFFFFF80000000
 Int64 subtract = max - min;
 Console.WriteLine(subtract.ToString("X16")); //00000000FFFFFFFF <- not an overflow since it's a 64 bit number
 Int32 neg = -1
 Console.WriteLine(neg.ToString("X")); //FFFFFFFF

Here you see that if you just 5 subtract the hex values) in 2's complement 4 you get the number that's -1 in a 32 bit 3 number. (after trunkating the leading 0's 2

2's complement arithmetic can be very fun 1 http://en.wikipedia.org/wiki/Two's_complement

More Related questions