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

后端 未结 3 1974
悲哀的现实
悲哀的现实 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:55

    Section 7.72 (Division Operator) of the C# 4 specs states:

    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, [...]. 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.

    So the fact that this throws an exception in an unchecked context is not in fact a bug, since the behavior is implementation-defined.

提交回复
热议问题