5

In 7.8.3. of the C# Specification regarding the Remainder operator it states the following:

If the left operand is the smallest int or long value and the right operand is -1, a System.OverflowException is thrown.

Therefore int.MinValue % -1 would result in an OverflowException. I am trying to understand why?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Dirk Strauss
  • 630
  • 1
  • 8
  • 19
  • Note that in Java, the result is `0` by specifications and in C the operation invokes undefined behavior. – ouah Nov 25 '15 at 23:29

1 Answers1

6

In two's complement arithmetic, data types have a range from (-2**n) to (2**n - 1) (where 'n' is 1 less than the number of bits in the data type).

For example, a 16-bit signed integer has a valid range from -32768 (-2**15) to 32767 (2**15 - 1).

-32768 / -1 = +32768 which exceeds the valid range for a 16-bit signed integer.

keithmo
  • 4,893
  • 1
  • 21
  • 17
  • 2
    Mathematically `int.MinValue % -1` would be 0, or -1 (or possible 1). This does not exceed the valid range for a 16-bit signed integer. – chux - Reinstate Monica Nov 25 '15 at 23:29
  • 2
    But it's typically computed by first dividing then finding the remainder. – keithmo Nov 25 '15 at 23:31
  • Agree, but does the language specification require that order? – chux - Reinstate Monica Nov 25 '15 at 23:39
  • That I don't know. I'm a little surprised that C# doesn't handle it properly. – keithmo Nov 25 '15 at 23:41
  • I suspect C# inherited C's specification: If `a/b` is not representable, then `a%b` is also undefined even if `a%b` is representable. – chux - Reinstate Monica Nov 25 '15 at 23:43
  • @chux I suspect they specified like this for performances reasons because on x86 and x64 the remainder can be obtained from the integer division processor instruction that computes in the same time the division and the remainder. – ouah Nov 25 '15 at 23:48
  • It makes sense to define the tautology `a == a/b + a%b` – Barmar Nov 25 '15 at 23:48
  • 1
    http://stackoverflow.com/questions/31775042/why-does-the-c-sharp-specification-leave-int-minvalue-1-implementation-defi?lq=1 goes into details – chux - Reinstate Monica Nov 25 '15 at 23:54
  • @chux thank you for the answers. I was looking at this from a mathematical point of view and couldn't understand why C# treated it differently. Thank you for the link. – Dirk Strauss Nov 26 '15 at 09:01
  • @keithmo your answer above rocks, thanks mate! – Dirk Strauss Nov 26 '15 at 09:01
  • This is at best an incomplete answer. It discusses only why integer division might not work, while ignoring how and why that might impact the remainder operation. The question asked relates specifically to the remainder operation. – Hammerite Jul 01 '16 at 09:58