According to CERT C++ Secure Coding Standard modulus can can overflow it says:
[...]Overflow can occur during a modulo operation when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to -1.
and they recommend the follow style of check to prevent overflow:
signed long sl1, sl2, result;
/* Initialize sl1 and sl2 */
if ( (sl2 == 0 ) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
/* handle error condition */
}
else {
result = sl1 % sl2;
}
The C++ draft standard section 5.6
Multiplicative operators paragraph 4 says(emphasis mine):
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. For integral operands the / operator yields the algebraic quotient with any fractional part discarded;81 if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both a/b and a%b is undefined.
The C version of the CERT document provides some more insight on how %
works on some platforms and in some cases INT_MIN % -1
could produce a floating-point exception.
The logic for preventing overflow for / is the same as the above logic for %
.