public static void Main()
int i = int.MinValue;
System.Console.WriteLine(i * -1);
System.Console.WriteLine(i / -1);
Why does div throw an OverflowException when you're trying to divide MinInt by -1? I'm assuming that since dividing by zero throws a DivideByZeroException, the CLR designers thought it would be nice if div would throw an exception for overflow as well.
Partition III CIL.doc section 3.31 about div says:
Integral operations throw ArithmeticException if the result cannot be represented in the result type. This can happen if value1 is the maximum negative value, and value2 is -1.
Integral operations throw DivideByZeroException if value2 is zero.
Implementation Specific (Microsoft)
On the x86 an OverflowException is thrown when computing (minint div 1).
Why didn't they define a div.ovf (like there are add.ovf, sub.ovf, mul.ovf, etc.) in addition to div (and then make div behave consistently with add, sub & mul)?
Question: What should I do? Implement Java's idiv bytecode using this broken div or compile them into conditional code that checks for MinInt / -1 and treats that specially (and thus slowing down integer division).
BTW, J# uses div but I'm not sure they actually thought about this issue. The following code crashes the J# compiler:
System.out.println(Integer.MIN_VALUE / - 1);