Can't Mod Zero?

Dasaru picture Dasaru · Sep 10, 2011 · Viewed 57.5k times · Source

Why is X % 0 an invalid expression?

I always thought X % 0 should equal X. Since you can't divide by zero, shouldn't the answer naturally be the remainder, X (everything left over)?

Answer

Nawaz picture Nawaz · Sep 10, 2011

The C++ Standard(2003) says in §5.6/4,

[...] If the second operand of / or % is zero the behavior is undefined; [...]

That is, following expressions invoke undefined-behavior(UB):

X / 0; //UB
X % 0; //UB

Note also that -5 % 2 is NOT equal to -(5 % 2) (as Petar seems to suggest in his comment to his answer). It's implementation-defined. The spec says (§5.6/4),

[...] If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.