我刚开始自学C++,并开始学习整数溢出。出于好奇,我编写了一些测试来查看特定整数值的情况。
这是我的程序:
#include <iostream>
int main()
{
int x(0);
std::cout << x << std::endl;
x = x + 2147483647;
std::cout << x << std::endl;
x = x + 1;
std::cout << x << std::endl;
std::cout << std::endl;
unsigned int y(0);
std::cout << y << std::endl;
y = y + 4294967295;
std::cout << y << std::endl;
y = y + 1;
std::cout << y << std::endl;
}
以下是输出结果:
0
2147483647
-2147483648
0
4294967295
0
输出结果让我有些惊讶,我在想是否有人能解释一下为什么会出现这种情况,或者说这些结果的意外性是预料之中的;所以这可能只是由于我的特定机器造成的。