Module overflow?

I know that (INT_MIN / -1) is overflowing, but (INT_MIN% -1) is 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 standard behavior defined, or is this implementation defined? Also, is there ANY OTHER case where the division operation will overflow? and is there a case where the module operator will overflow?

+6
source share
3 answers

According to CERT C ++ Secure Coding Standard module may overflow , he says:

[...] Overflow can occur during operations with the module, when the dividend is equal to the minimum (negative) value for the integer type with a sign, and the divisor is -1.

and they recommend that you follow the following checkout style 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; } 

draft C ++ standard section 5.6 Multiplicative operators given in clause 4 say (emphasis mine):

The binary / operator gives the quotient, and the binary operator% gives the remainder of dividing the first expression by the second. If the second operand / or% is zero, the behavior is undefined. For integral operands, the operator / gives an algebraic relation with any fractional part discarded: 81 if the quotient a / b is representable in the result type (a / b) * b + a% b is equal to a; otherwise, the behavior of both a / b and a% b will be undefined.

The C version of the CERT document provides more details on how % works on some platforms, and in some cases INT_MIN % -1 can throw a floating point exception.

The overflow prevention logic for / is the same as in the above logic for % .

+10
source

This is not a modulo operation that causes an overflow:

 int x = INT_MIN; int a = x / -1; // int are 2 complement, so this is effectively -INT_MIN which overflows int b = x % -1; // there is never a non-0 result for a anything +/- 1 as there is no remainder 
+1
source

Each modern implementation of the C ++ language uses two additions as the main scheme for representing integers. As a result, -INT_MIN is never represented as an int. (INT_MAX is -1 + INT_MIN). Overflow occurs because the value x / -1 cannot be represented as int when x is INT_MIN.

Think about what% calculates. If the result can be represented as int, there will be no overflow.

0
source

Source: https://habr.com/ru/post/955636/


All Articles