这个检测整数加法溢出的函数真的有用吗?

Does this function for detecting integer addition overflow actually work?

在阅读 , I came across a link to the comp.lang.c FAQ 的评论时显示 "careful addition function" 据称检测到整数溢出:

int
chkadd(int a, int b)
{
    if (INT_MAX - b < a) {
        fputs("int overflow\n", stderr);
        return INT_MAX;
    }
    return a + b;
}

如果b == -1这怎么不溢出?如果假设 ab 都是正数,为什么首先要使它们 int 而不是 unsigned int

可能他们只是忽略了它。 Additional links FAQ 页面上似乎提供了更正确的代码。

OP 已确定 INT_MAX - b 可能会溢出,从而使剩余代码无法进行正确的溢出检测。它不起作用。

if (INT_MAX - b < a) {  // Invalid overflow detection

无UB检测溢出的方法如下:

int is_undefined_add1(int a, int b) {
  return (a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a);
}

why make them int rather than unsigned int in the first place?

更改为 unsigned 并不能解决问题 一般 unsigned: [0...UINT_MAX]的范围可以是int: [INT_MIN...INT_MAX]的一半。 IOW:INT_MAX == UINT_MAX。现在这样的系统很少见。 IAC,不需要更改类型,因为编码为 is_undefined_add1()