当我混合签名和无符号类型时会发生什么? [英] what happens when i mix signed and unsigned types ?

查看:212
本文介绍了当我混合签名和无符号类型时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习C ++语言,我对类型转换有一些疑问,你能解释一下这样的表达式会发生什么:

I'm studying the C++ language and i have some doubt about type conversion, could you explain me what happens in an expression like this :

unsigned int u = 10; 
int a = -42; 
std::cout << u - a << std::endl;

在这里,我知道如果我应用规则,当我们有两个数学运算符时,结果将是52。但我不知道当编译器转换为无符号值创建一个无符号类型的临时,会发生什么发生后会发生什么?现在的表达式应该是10 -4294967254。

Here i know that the result will be 52 if i apply the rules when we have two mathematical operators.But i wonder what happens when the compiler to convert a to an unsigned value creates a temporary of unsigned type, what happens after ? The expression now should be 10 -4294967254.

推荐答案

简单来说,如果你混合类型相同 int long int long long int 无符号类型wins,并且在该无符号类型中执行计算。结果是相同的无符号类型。

In simple terms, if you mix types of the same rank (in the sequence of int, long int, long long int), the unsigned type "wins" and the calculations are performed within that unsigned type. The result is of the same unsigned type.

如果混合不同排名的类型,排名较高的类型wins,如果它可以表示所有lower-排名类型。计算在该类型内执行。

If you mix types of different rank, the higher-ranked type "wins", if it can represent all values of lower-ranked type. The calculations are performed within that type. The result is of that type.

最后,如果排名较高的类型不能表示较低排名类型的所有值,则较高排名类型的无符号版本是用过的。

Finally, if the higher-ranked type cannot represent all values of lower-ranked type, then the unsigned version of the higher ranked type is used. The result is of that type.

在你的情况下,你混合了相同排名的类型( int unsigned int ),这意味着整个表达式在 unsigned int 类型中求值。正如你正确说的,表达式现在是 10 - 4294967254 (对于32位 int )。无符号类型遵循模运算规则, 2 ^ 32 4294967296 )作为模。如果你仔细计算结果(可以算术表达为 10 - 4294967254 + 4294967296 ),它将会显示为预期 52

In your case you mixed types of the same rank (int and unsigned int), which means that the whole expression is evaluated within unsigned int type. The expression, as you correctly stated, is now 10 - 4294967254 (for 32 bit int). Unsigned types obey the rules of modulo arithmetic with 2^32 (4294967296) as the modulo. If you carefully calculate the result (which can be expressed arithmetically as 10 - 4294967254 + 4294967296), it will turn out as the expected 52.

这篇关于当我混合签名和无符号类型时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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