What happens if I assign a negative value to an unsigned variable?(如果将负值赋给无符号变量会发生什么?)
问题描述
我很想知道如果我将一个负值赋给一个无符号变量会发生什么.
I was curious to know what would happen if I assign a negative value to an unsigned variable.
代码看起来有点像这样.
The code will look somewhat like this.
unsigned int nVal = 0;
nVal = -5;
它没有给我任何编译器错误.当我运行程序时,nVal 被分配了一个奇怪的值!会不会是一些 2 的补码值被分配给了 nVal?
It didn't give me any compiler error. When I ran the program the nVal was assigned a strange value! Could it be that some 2's complement value gets assigned to nVal?
推荐答案
官方回答 - 第 4.7 节 conv.integral
For the official answer - Section 4.7 conv.integral
"如果目标类型是无符号的,则结果值是与源整数一致的最小无符号整数(模 2n 其中 n 是使用的位数来表示无符号类型.[注意:在二进制补码表示中,这种转换是概念性的,位模式没有变化(如果没有截断).-end note]
"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2n where
nis 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 ]
这实质上意味着,如果底层架构存储在不是二进制补码的方法中(如有符号幅度或一个补码),则转换为无符号的行为必须表现得好像它是二进制补码一样.
This essentially means that if the underlying architecture stores in a method that is not Two's Complement (like Signed Magnitude, or One's Complement), that the conversion to unsigned must behave as if it was Two's Complement.
这篇关于如果将负值赋给无符号变量会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果将负值赋给无符号变量会发生什么?
 
				
         
 
            
        基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				