unsigned int 和signed char 比较
我试图将无符号 int 与有符号 char 进行比较,如下所示:
int main(){
unsigned int x = 9;
signed char y = -1;
x < y ? printf("s") : printf("g");
return 0;
}
我期望 o/p 为“g”。相反,它是“s”。这里进行了什么样的转换?
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;
}
I was expecting the o/p to be "g". Instead, its "s". What kind of conversion is done here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C99 的
6.3.1.8
节“常规算术转换” 详细介绍了隐式整数转换。这不算数,因为它们是不同的类型。
这不算数,因为一个已签名,另一个未签名。
宾果游戏。
x
的等级高于y
,因此 y 被提升为unsigned int
。这意味着它从-1
转变为UINT_MAX
,远大于 9。其余规则不适用,因为我们已经找到了匹配项,但我将包括为了完整性:
与此问题相关的排名如下所示。所有排名均在 C99 的
6.3.1.1
部分、布尔值、字符和整数 中详细介绍,因此您可以参考该内容了解更多详细信息。Section
6.3.1.8
, Usual arithmetic conversions, of C99 details implicit integer conversions.That doesn't count since they're different types.
That doesn't count since one is signed, the other unsigned.
Bingo.
x
has a higher rank thany
so y is promoted tounsigned int
. That means that it morphs from-1
intoUINT_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:
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.我的猜测是 y 被提升为 unsigned int ,这成为一个很大的值(由于包装)。因此条件满足。
My guess is
y
is promoted tounsigned int
which becomes a big value (due to wrapping). Hence the condition is satisfied.运行以下代码:
输出为:
转换后,y 取一个非常大的值。这就是为什么输出是s。
Ran the following code:
The output is:
After a casting, y takes a very large value. That is why output is s.
char 被提升为 unsigned int,值为 MAX_UINT,大于 9。
The char is promoted to unsigned int, with a value of MAX_UINT, which is greater than 9.