In C++ binary operators for intrinsic types, both operands should have the same type, if not, one of the operands get converted to the other operand’s type based on a hierarchy:
long double
double
float
unsigned long long int
long long int
unsigned long int
long int
unsigned int
int
My Question is: Why unsigned T is in a higher level than T . is it just an arbitrary choice or there is some advantages in converting T to Unsigned T and not the other way around.
Update:
//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.*/
So I dont see how convering T to Unsigned T has more advantages than the other way around.
It is essentially an arbitrary choice that goes back to the early days of C.
As far as I can determine, in pre-standard K&R C the rule basically was that if an operand of a operator had a unsigned type, then the result would also be unsigned (this is called unsigned-preserving).
When C got standardized, this rule was changed to the rule currently used by both C and C++, which allows the unsigned property to get dropped, as long as the value can be represented in the target type (this is called value-preserving). The reason was that the new rules provide fewer surprises for the unsuspecting programmers when doing mixed signed/unsigned arithmetic.
The conversion from
Ttounsigned Tcan have two interpretations:unsigned long longfor stuff like:1ULL > -1LL, because the signed to unsigned conversion is always defined (by virtue of the wrap-around feature of unsigned integers), but the reverse conversion is not.