Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

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