Why dividing int.MinValue by -1 threw OverflowException in unchecked context?

后端 未结 3 1967
悲哀的现实
悲哀的现实 2020-12-08 02:28
int y = -2147483648;
int z = unchecked(y / -1);

The second line causes an OverflowException. Shouldn\'t unchecked prevent

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 02:46

    According to section 7.8.2 of the C# Language Specification 5.0 we have the following case:

    7.8.2 Division operator
    For an operation of the form x / y, binary operator overload resolution (§7.3.4) is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator. The predefined division operators are listed below. The operators all compute the quotient of x and y.

    • Integer division:
      int operator /(int x, int y);
      uint operator /(uint x, uint y);
      long operator /(long x, long y);
      ulong operator /(ulong x, ulong y);
      If the value of the right operand is zero, a System.DivideByZeroException is thrown. The division rounds the result towards zero. Thus the absolute value of the result is the largest possible integer that is less than or equal to the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs. If the left operand is the smallest representable int or long value and the right operand is –1, an overflow occurs. In a checked context, this causes a System.ArithmeticException (or a subclass thereof) to be thrown. In an unchecked context, it is implementation-defined as to whether a System.ArithmeticException (or a subclass thereof) is thrown or the overflow goes unreported with the resulting value being that of the left operand.

提交回复
热议问题