gpt4 book ai didi

c++ - 模数是否溢出?

转载 作者:可可西里 更新时间:2023-11-01 18:25:35 24 4
gpt4 key购买 nike

我知道 (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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com