To my understanding, that should give you an overflow error and when I write it like this:
public static void Main() { Console.WriteLine(int.MaxValue - int.MinValue); }
it does correctly give me an overflow error.
However:
public static void Main() { Console.WriteLine(test()); } public static Int32 test(int minimum = int.MinValue, int maximum = int.MaxValue) { return maximum - minimum; }
will output -1 Why does it do this? It should throw an error because its clearly an overflow!
The MinValue property or Field of Int32 Struct is used to represent the minimum possible value of Int32. The value of this field is constant means that a user cannot change the value of this field. The value of this field is -2,147,483,648. Its hexadecimal value is 0x80000000.
In computing. The number 2,147,483,647 (or hexadecimal 7FFFFFFF16) is the maximum positive value for a 32-bit signed binary integer in computing. It is therefore the maximum value for variables declared as integers (e.g., as int ) in many programming languages.
MAX_VALUE in Java Required? It is used to automatically assign any variable the maximum integer possible without requiring to remember the exact number. There are many times when we need a maximum or minimum number.
(Arithmetic) Integer Overflows An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
int.MaxValue - int.MinValue
= a value which int cannot hold. Thus, the number wraps around back to -1.
It is like 2147483647-(-2147483648) = 4294967295 which is not an int
Int32.MinValue Field
The value of this constant is -2,147,483,648; that is, hexadecimal 0x80000000.
And Int32.MaxValue Field
The value of this constant is 2,147,483,647; that is, hexadecimal 0x7FFFFFFF.
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.
This is because of compile-time overflow checking of your code. The line
Console.WriteLine(int.MaxValue - int.MinValue);
would not actually error at runtime, it would simple write "-1", but due to overflow checking you get the compile error "The operation overflows at compile time in checked mode".
To get around the compile-time overflow checking in this case you can do:
unchecked { Console.WriteLine(int.MaxValue - int.MinValue); }
Which will run fine and output "-1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With