1

在内部类型的 C++ 二元运算符中,两个操作数应该具有相同的类型,如果不是,则其中一个操作数将根据层次结构转换为另一个操作数的类型:

long double
double
float
unsigned long long int
long long int
unsigned long int
long int
unsigned int
int

我的问题是:为什么unsigned TT. 它只是一个任意的选择,还是转换TUnsigned T而不是相反有一些优势。

更新:

//where `unsigned int` to `int` work better.
int a=-3;
unsigned int b=3;
cout << a+b; /* this will output the right result if b get converted to int,
which is not what really happen.*/

//where `int` to `unsigned int` work better.
int a=3;
unsigned int b=pow(2,20);
cout << a+b; /* this will output the right result if a get converted to unsigned int,
which is fortunately what really happen.*/

因此,我看不出与其他方式相比,convering TtoUnsigned T具有更多优势。

4

2 回答 2

4

它本质上是一个任意的选择,可以追溯到 C 的早期。

据我所知,在准标准 K&R C 中,规则基本上是,如果运算符的操作数具有无符号类型,则结果也将是无符号的(这称为无符号保留)。

当 C 标准化时,该规则更改为 C 和 C++ 目前使用的规则,允许删除无符号属性,只要值可以在目标类型中表示(这称为值保留)。原因是新规则在执行混合有符号/无符号算术时为毫无戒心的程序员提供了更少的惊喜。

Tto的转换unsigned T可以有两种解释:

  1. 它是旧(未签名保留)规则的延续。
  2. 这是唯一明智的做法,它不需要比unsigned long long以下内容更大的类型:1ULL > -1LL,因为始终定义有符号到无符号的转换(凭借无符号整数的环绕特性),但反向转换不是.
于 2012-12-22T16:43:24.747 回答
0

我猜逻辑是因为 MSB 用于符号,所以实际大小int比 of 小 1 位。unsigned int因此,有符号变量的绝对值范围是无符号变量范围的一半。

于 2012-12-22T16:14:14.017 回答