我很想知道如果我将一个负值赋给一个无符号变量会发生什么。
代码看起来有点像这样。
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/