如果我为一个无符号变量赋值一个负值会发生什么? [英] What happens if I assign a negative value to an unsigned variable?

查看:367
本文介绍了如果我为一个无符号变量赋值一个负值会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

  unsigned int nVal = 0; 
nVal = -5;

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

解决方案

正式答案 - 第4.7节[conv.integral]


如果目标类型是无符号,结果值是最小无符号整数等于源整数(模2 ^ n,其中n是用于表示无符号类型的位数)[注:在二进制补码表示中,此转换是概念性的,并且位模式没有变化没有截断)。-end note]



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;

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?

解决方案

For the official answer - Section 4.7 [conv.integral]

"If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n 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 ]

这篇关于如果我为一个无符号变量赋值一个负值会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆