c++cinteger-division

What is the remainder after division by zero?


I know that division by zero is not allowed in math, but can I use modulo by zero and what answer should I get?

For example

10 % 0 = ?
5 % 0 = ?

Solution

  • The standard defines it as "undefined".

    In nearly all processors, the modulo is performed by the same functionality as divide. In modern larger processors, it's an instruction (x86 for example). Most often, this instruction will cause a trap when dividing by zero, and this applies whether the code is "intending to use the modulo" or "quotient" part.

    It is undefined so that processors and compilers have the freedom to implement what they fancy - e.g. if the processor just returns whatever came in as the input, that's also allowed, or if it causes the entire OS to crash, that's "fine" too by the standard.

    In summary, modulo of zero is just as bad as divide by zero.

    (Note that typically, floating point divide by zero does NOT trap [by default], and produces a infinity value, except if the value divided is also zero, in which case you get "not a number")