Question

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 = ?
Was it helpful?

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")

OTHER TIPS

In C/C++ it is Undefined behaviour, you can get various of results depending on compiler or even different instances of same program.

C11dr §6.5.5

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined

The result is UB

C11dr §6.5.5 "The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined."

Mathematically speaking you should get infinite, which is the correct answer... programmatically any sane compiler will warn you of division by zero as internally the modulo operator (at least in C/C++) is translated in a division (in most implementations). So the answer to your question is that you would get a floating point exception, in both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top