When attempting to apply the negative operator (-) to a number with the minimum int value (-2147483648
), it is completely ignored instead of throwing an OverflowException
. For example, I have the following code:
int temp = int.MinValue;//-2147483648
int temp2 = -temp;//Should evaluate to 2147483648, which would throw an OverflowException, but instead is ignored and returns -2147483648
The temp
variable is assigned the value -2147483648
, which is the minimum value for the int
type & is perfectly valid. The temp2
variable, however, should throw an OverflowException
because 2147483648
>int.MaxValue
. Instead, the negative operator (-) is ignored & temp2
ends up with a value of -2147483648
(int.MinValue
, the same as temp). The same problem occurs if I multiply by -1 instead:
int temp2 = -1 * temp;//Same problem as above
Everything works as expected when temp
is a positive value or a value greater than int.MinValue
, and -int.MinValue
gives a compile-time error (as expected). Why is the negative operator ignored instead of throwing an OverflowException
?
There is a possibility to let the system throw an exception in this case:
checked(int.MinValue * -1)
will throw the exception
instead of:
unchecked(int.MinValue * -1)
will give the result of -2147483648 and no exception.
The reason why your code does not throw the exception by default is that you might disabled checking in your project-file.
Look for:
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
in your *.csproj-file.
See also the link to learn.microsoft
given in the answer of Rand-Random
See also Compiler Options