减法时整数溢出的种类

时间:2010-10-20 22:16:59

标签: c++ integer integer-overflow

我正在尝试再次学习C ++,在21天内使用Sams Teach Yourself C ++(第6版)。我正在努力完成它,确保我理解每一章(尽管我已经熟悉了C语法语言)。

在第5章(代码清单5.2)的开头附近,有一个关于无符号整数溢出的观点。基于他们的例子,我写了这个:

#include <iostream>

int main () {
    unsigned int bignum = 100;
    unsigned int smallnum = 50;
    unsigned int udiff;
    int diff;
    udiff = bignum - smallnum;
    std::cout << "Difference (1) is " << udiff << "\n";
    udiff = smallnum - bignum;
    std::cout << "Difference (2) is " << udiff << "\n";
    diff = bignum - smallnum;
    std::cout << "Difference (3) is " << diff << "\n";
    diff = smallnum - bignum;
    std::cout << "Difference (4) is " << diff << "\n";
    return 0;
}

这给出了以下输出,这对我来说并不奇怪:

Difference (1) is 50
Difference (2) is 4294967246
Difference (3) is 50
Difference (4) is -50

如果我更改程序以使声明bignum的行改为unsigned int bignum = 3000000000;,那么输出就是

Difference (1) is 2999999950
Difference (2) is 1294967346
Difference (3) is -1294967346
Difference (4) is 1294967346

第一个显然很好。 数字1294967346的解释是1294967346正是2^32 - 3000000000。我不明白为什么第二行没有读1294967396,因为smallnum贡献了50。

第三次和第四行我无法解释。这些结果是如何产生的?

编辑:对于第三行 - 它是否只是通过找到符合有符合条件的int允许的值范围的解模mod 2^32来提供此结果?

1 个答案:

答案 0 :(得分:1)

2 ^ 32 - 3000000000 = 1294967296(!)