原始类型限制安全
Primitive types limit safety
考虑到我正在编译一个 32 位应用程序(即使它没有改变任何东西),这段代码安全吗?
cout << (numeric_limits<unsigned int>::max() + 1) << endl;
它打印“0”但确实影响了另一个变量?假设我有一个包含以下位的字节 (char),然后我添加 1:1111 1111 (255)。结果会是“1 0000 0000”(256) 并且 cpu 只会读取最后 8 位作为我的变量还是只会重置位序列?
无符号整数类型遵循算术模 2^N 的法则。这种情况下的结果将始终为 0,不会覆盖其他内存。
C++ 标准草案,§3.9.1.4 要求
Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.
所以你问题中的代码需要输出0,符合模运算法则的要求。
请注意,上述规则不适用于 char
,因为它未声明为 unsigned
(您需要使用 unsigned char
)。
考虑到我正在编译一个 32 位应用程序(即使它没有改变任何东西),这段代码安全吗?
cout << (numeric_limits<unsigned int>::max() + 1) << endl;
它打印“0”但确实影响了另一个变量?假设我有一个包含以下位的字节 (char),然后我添加 1:1111 1111 (255)。结果会是“1 0000 0000”(256) 并且 cpu 只会读取最后 8 位作为我的变量还是只会重置位序列?
无符号整数类型遵循算术模 2^N 的法则。这种情况下的结果将始终为 0,不会覆盖其他内存。
C++ 标准草案,§3.9.1.4 要求
Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.
所以你问题中的代码需要输出0,符合模运算法则的要求。
请注意,上述规则不适用于 char
,因为它未声明为 unsigned
(您需要使用 unsigned char
)。