I know that (INT_MIN / -1) overflows, but (INT_MIN % -1) does not. At least this is what happens in two compilers, one pre-c++11 (VC++ 2010) and the other post-c++11 GCC 4.8.1
int x = INT_MIN;
cout << x / -1 << endl;
cout << x % -1 << endl;
Gives:
-2147483648
0
Is this behavior standard defined or this is implementation defined? Also is there ANY OTHER case where the division operation would overflow? and is there any case where the modulus operator would overflow?
The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y. Return Value: If y completely divides x, the result of the expression is 0.
The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division.
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).
We can multiply recursively to overcome the difficulty of overflow. To multiply a*b, first calculate a*b/2 then add it twice. For calculating a*b/2 calculate a*b/4 and so on (similar to log n exponentiation algorithm).
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;81if 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 %
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With