【发布时间】:2026-02-23 08:20:03
【问题描述】:
#include <iostream>
using namespace std;
int main() {
unsigned char char_values[2] = {0, 255};
char_values[1] += 1;
cout << (int)char_values[0] << endl;
cout << (int)char_values[1] << endl;
return 0;
}
在这段代码中,我期望:
1
0
因为十进制的 255 是二进制的 1111 1111,十进制的 255 + 1 是二进制的 1 0000 0000。所以我认为char[0]会因为溢出而受到char[1]的影响,但结果是:
0
0
溢出会影响其他变量吗?
【问题讨论】:
-
那不是有效的 C++...
-
当创建一个应该构建的Minimal, Complete, and Verifiable Example 时,确保它确实是。
-
你是怎么得到这个来打印任何东西的? I only get errors.
-
至于你的问题,没有。无符号整数溢出只会包装溢出的值,不会发生其他任何事情。如果您将数组视为单个
unsigned short值,那么它会像您预期的那样(当然取决于 endianness)。 -
你确定这段代码能编译吗???
标签: c++ integer-overflow