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?

1
  • Note that in Java, the result is 0 by specifications and in C the operation invokes undefined behavior. Commented Nov 25, 2015 at 23:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

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.
But it's typically computed by first dividing then finding the remainder.
Agree, but does the language specification require that order?
That I don't know. I'm a little surprised that C# doesn't handle it properly.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.