Why does C++ output negative numbers when using modulo?

On x86 (and other processor architectures), integer division and modulo are carried out by a single operation, idiv (div for unsigned values), which produces both quotient and remainder (for word-sized arguments, in AX and DX respectively). This is used in the C library function divmod, which can be optimised by the compiler to a single instruction!

Integer division respects two rules:

  • Non-integer quotients are rounded towards zero; and
  • the equation dividend = quotient*divisor + remainder is satisfied by the results.

Accordingly, when dividing a negative number by a positive number, the quotient will be negative (or zero).

So this behaviour can be seen as the result of a chain of local decisions:

  • Processor instruction set design optimises for the common case (division) over the less common case (modulo);
  • Consistency (rounding towards zero, and respecting the division equation) is preferred over mathematical correctness;
  • C prefers efficiency and simplicitly (especially given the tendency to view C as a “high level assembler”); and
  • C++ prefers compatibility with C.

Leave a Comment