c++ - 模数是否溢出?

标签 c++ visual-c++ c++11 integer-overflow

我知道 (INT_MIN/-1) 会溢出,但 (INT_MIN % -1) 不会。至少这是在两个编译器中发生的情况,一个是 c++11 之前的版本 (VC++ 2010),另一个是 c++11 之后的 GCC 4.8.1

int x = INT_MIN;
cout << x / -1 << endl; 
cout << x % -1 << endl;

给予:

-2147483648
0

这个行为标准是定义的还是实现定义的? 还有除法运算会溢出的其他情况吗? 模运算符是否会溢出?

最佳答案

根据 CERT C++ Secure Coding Standard模 jar can overflow它说:

[...]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.

他们推荐以下检查方式来防止溢出:

signed long sl1, sl2, result;

/* Initialize sl1 and sl2 */

if ( (sl2 == 0 ) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
  /* handle error condition */
}
else {
  result = sl1 % sl2;
}

C++ draft standard 5.6 乘法运算符 段落 4 说(强调我的):

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.

C version of the CERT document提供了一些关于 % 在某些平台上如何工作的更多见解,在某些情况下 INT_MIN % -1 可能产生浮点异常。。 p>

preventing overflow for / 的逻辑与上述%的逻辑相同。

关于c++ - 模数是否溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19285163/

相关文章:

c++ - 迭代器取消引用的 decltype 编译错误

c++ - 如何将 std::shared_ptr<Resource> 传递给函数?

c++ - 使用 C++ 如何从 void 函数传递值?

c++ - C/C++ 控制台 Windows WIN32

c++ - c++读写同一个文件

c++ - 函数指针类型不能用于函数原型(prototype)

c++ - 具有重载成员函数的多线程

c++ - 在 C++ 中调用临时对象的析构函数的顺序是什么?

c++ - Arduino/C++ 交叉函数变量

c++ - 代码使用 g++ 编译但使用 VC++ 10 失败