gpt4 book ai didi

c - 为什么 x - y 在这个函数中不会溢出 TMin?为什么在这种情况下功能错误?

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:08 24 4
gpt4 key购买 nike

我正在阅读有关此功能的信息:

int tadd_ok ( int x, int y ) {  
int sum = x + y;
int negative_overflow = x < 0 && y < 0 && sum >= 0;
int positive_overflow = x >=0 && y >= 0 && sum < 0;
return !negative_overflow && !positive_overflow;
}

当我们将 TMin(即最小的 2 的补码)作为 y 的参数传递时,此函数会出现问题。
在这种情况下,当传入时 -y 将是 -y 即仍然是 TMin 第一个条件将表明我们对 x 的负值有负溢出。
然后我读到在这些情况下实际上“x - y 不会溢出”。

我的理解是这个函数的问题是没有考虑传递最小负数的corner case。我可以看到它会返回一个 negative_overflow 我不明白/不明白为什么这是错误的。
谁能帮助我理解这一点?

最佳答案

您不能事后检查有符号整数溢出,您必须在执行操作之前进行检查。这是因为算术运算中的有符号整数溢出是 undefined behavior在 C 和 C++ 中。一旦您调用了未定义的行为,您的程序的结果将变得不可预测 ( see my comment above for one of the most unexpected results I have seen )。对于 C,我们可以通过转到 draft C99 standard 来查看。 6.5 Expressions 部分说:

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.

证书提供了关于如何防止签名溢出的可靠指南:INT32-C. Ensure that operations on signed integers do not result in overflow对于添加,文档建议使用以下方法:

#include <limits.h>

void f(signed int si_a, signed int si_b) {
signed int sum;
if (((si_b > 0) && (si_a > (INT_MAX - si_b))) ||
((si_b < 0) && (si_a < (INT_MIN - si_b)))) {
/* Handle error */
} else {
sum = si_a + si_b;
}
/* ... */
}

该文档涵盖了所有可能的溢出操作,并为每种情况提供了建议。

关于c - 为什么 x - y 在这个函数中不会溢出 TMin?为什么在这种情况下功能错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25964066/

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