unsigned int 和 signed char 比较 [英] unsigned int and signed char comparison
问题描述
我正在尝试将 unsigned int 与有符号 char 进行比较,如下所示:
I am trying to compare an unsigned int with a signed char like this:
int main(){
unsigned int x = 9;
signed char y = -1;
x < y ? printf("s") : printf("g");
return 0;
}
我原以为 o/p 是g".相反,它的s".这里做了什么样的转换?
I was expecting the o/p to be "g". Instead, its "s". What kind of conversion is done here?
推荐答案
6.3.1.8
部分,C99 的常用算术转换详细介绍了隐式整数转换.
Section 6.3.1.8
, Usual arithmetic conversions, of C99 details implicit integer conversions.
如果两个操作数的类型相同,则不需要进一步转换.
If both operands have the same type, then no further conversion is needed.
这不算数,因为它们是不同的类型.
That doesn't count since they're different types.
否则,如果两个操作数都是有符号整数类型或都具有无符号整数类型,则整数转换等级较小的操作数将转换为等级较大的操作数的类型.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
这不算数,因为一个已签名,另一个未签名.
That doesn't count since one is signed, the other unsigned.
否则,如果无符号整数类型的操作数的秩大于或等于另一个操作数类型的秩,则将有符号整数类型的操作数转换为无符号整数类型的操作数的类型.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
宾果游戏.x
的排名高于 y
,因此 y 被提升为 unsigned int
.这意味着它从 -1
变形为 UINT_MAX
,大大大于 9.
Bingo. x
has a higher rank than y
so y is promoted to unsigned int
. That means that it morphs from -1
into UINT_MAX
, substantially larger than 9.
其余的规则不适用,因为我们找到了我们的匹配,但为了完整起见,我将它们包括在内:
The rest of the rules don't apply since we have found our match but I'll include them for completeness:
否则,如果有符号整数类型的操作数的类型可以表示无符号整数类型的操作数的所有值,则将无符号整数类型的操作数转换为有符号整数类型的操作数的类型输入.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
否则,两个操作数都转换为与带符号整数类型的操作数类型对应的无符号整数类型.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
<小时>
与此问题相关的排名如下所示.所有等级都在 C99,6.3.1.1
部分,布尔值,字符和整数中详细说明,因此您可以参考以获取更多详细信息.
The ranks relevant to this question are shown below. All ranks are detailed in C99, section 6.3.1.1
, Boolean, character, and integers so you can refer to that for further details.
long long int
的rank要大于long int
的rank,即应大于int
的秩,该秩应大于short int
的秩,应大于signed char
.
The rank of
long long int
shall be greater than the rank oflong int
, which shall be greater than the rank ofint
, which shall be greater than the rank ofshort int
, which shall be greater than the rank ofsigned char
.
char
的等级应该等于signed char
和unsigned char
的等级.
The rank of char
shall equal the rank of signed char
and unsigned char
.
这篇关于unsigned int 和 signed char 比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!