簡體   English   中英

c ++內部類型之間的隱式類型轉換

[英]c++ implicit type conversion between intrinsic types

在內部類型的C ++二元運算符中,兩個操作數應該具有相同的類型,否則,其中一個操作數將根據層次結構轉換為另一個操作數的類型:

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

我的問題是:為什么unsigned T水平高於T 它只是一個隨意的選擇,或者將T轉換為Unsigned 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.*/

所以我不知道如何將TUnsigned T比其他方式更有優勢。

它本質上是一個任意選擇,可以追溯到C的早期。

據我所知,在預標准K&R C中,規則基本上是如果運算符的操作數具有無符號類型,則結果也將是無符號的(這稱為無符號保留)。

當C標准化時,此規則被更改為C和C ++當前使用的規則,只要該值可以在目標類型中表示(這稱為保留值),就可以刪除無符號屬性。 原因是新規則在進行混合有符號/無符號算術時為不知情的程序員提供了更少的驚喜。

Tunsigned T的轉換可以有兩種解釋:

  1. 它是舊的(未簽名的保留)規則的保留。
  2. 這是唯一理智的做法,它不需要大於unsigned long long的類型,例如: 1ULL > -1LL ,因為始終定義了signed to unsigned conversion(由於無符號整數的環繞特性) ,但反向轉換不是。

我猜想邏輯是int的實際大小比unsigned int小1位,因為MSB用於符號。 因此,有符號變量的絕對值范圍是無符號變量的范圍的一半。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM