Why Is 0 Mod 0 an Error?

If I type:

int main() { return 0 % 0; }

I get back an error:

error C2124: divide or mod by zero

What is the reason behind this? Isn't the answer zero?

14

3 Answers

In mathematics, x mod 0 is undefined, hence the error.

2

From C++ standard, section 5.5:

If during the evaluation of an expression the result is not mathematically defined or not in the range of representable mathematical values for its type, the behavior is undefined. [...] Treatment of division by zero, forming a remainder using a zero divider, and all floating point exceptions vary among machines, and is usually adjustable by a library function.

Since remainder of a division by zero is mathematically undefined regardless of the number being divided, the answer is undefined according to the C++ standard.

The mod function is effectively the same as the integer division function, except that it gives you the remainder, rather than the quotient. You can't divide by zero...

(BTW, as an aside, 0/0 is not even infinity, it's indeterminate.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest