c++ - 如果我为无符号变量分配负值会发生什么?

标签 c++ type-conversion integer unsigned signed

我很想知道如果我将一个负值赋给一个无符号变量会发生什么。

代码看起来有点像这样。

unsigned int nVal = 0;
nVal = -5;

它没有给我任何编译器错误。当我运行程序时, nVal 被分配了一个奇怪的值!会不会是一些 2 的补码被分配给 nVal

最佳答案

对于官方答案 - 第 4.7 节 conv.integral

"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ]

这实质上意味着,如果底层架构存储在非二进制补码的方法中(例如有符号幅度或二进制补码),则到无符号的转换必须表现得好像它是二进制补码一样。

关于c++ - 如果我为无符号变量分配负值会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2711522/

相关文章:

python - 将 `AMPL` 或 `GAMS` 文件转换为 `Python`

java - 如果字符已经是java中的数字,则将字符转换为整数

c++ - 从 Visual C++ 6 迁移到 Visual C++ 2008 Express

c++ - Windows 中的 Qt 共享库,不生成 .lib 文件

java - 将单个字节转换为字符串?

c++ - reinterpret_cast 是否保证它永远不会改变其操作数的值?

java - 获取用户输入的范围以进行随机生成

casting - Swift:CInt 到 Int 的转换?

c++ - 为什么我的连字符不能使用 std::cout 正确显示?

c++ - 创建具有多态性和 op 的模板。 C++中的重载