隐式转换如何与带符号字符和无符号int一起工作? [英] How implicit conversion work with signed character and unsigned int?

查看:129
本文介绍了隐式转换如何与带符号字符和无符号int一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
void main()
{
    unsigned x = 1;
    signed char y = -1;
    if(x  > y)
        printf("x > y");
    else if(x == y)
        printf("x == y");
    else
        printf("x < y");
    printf("\n");
    printf("%d",(signed char)x);
    printf("\n");
    printf("%d",(unsigned int)y);
}

OUTPUT:
x < y
1
-1

我希望输出为x == y,因为在比较期间有符号字符应该转换为unsigned int? 请向我解释x< y ...

I expected the output to be x == y as during comparison signed character is supposed to be converted to unsigned int? Please explain me how x < y...

推荐答案

我希望输出为x == y,因为在比较期间应该将有符号字符转换为无符号int?

好吧,您已经到了一半.

Well, you're halfway there.

-1的值转换(实际上是提升)为unsigned int时,表示形式会产生可通过类型表示的最大值.因此,提升的值变得大于x,即1.

When a value of -1 is converted (promoted, actually) to unsigned int, the representation produces the biggest possible value representable by the type. Hence, the promoted value becomes greater than x which is 1.

引用C11,第6.3.1.8章,常用算术转换

Quoting C11, chapter §6.3.1.8, Usual arithmetic conversions

否则,如果具有无符号整数类型的操作数的秩更大或 等于另一个操作数类型的等级,然后是 有符号整数类型将转换为无符号操作数的类型 整数类型.

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.

为澄清起见,升迁并不表示已删除签名.带符号的操作数(值)被视为提升的类型.该值由位表示确定.详细信息:第6.3.1.3节

To clarify, the promotion does not mean, it removes the signedness. The operand (value), with the sign, is treated as the promoted type. The value is determined from the bit representation. The details: chapter §6.3.1.3,

否则,如果新类型是无符号的,则通过重复加或 比新类型可以表示的最大值多减去一个 直到该值在新类型的范围内.

Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.


要添加到上面,用法


To add to above, the usage

printf("%d",(signed char)x);

printf("%d",(unsigned int)y);

不好. %d需要带符号的整数类型(int)作为参数.

are no good. %d expects a signed integer type (int) as argument.

  • 如果要打印signed char值,请使用%hhd
  • 如果要打印unsigned int,请使用%u
  • If you want to print a signed char value, use %hhd
  • If you want to print an unsigned int, use %u

这篇关于隐式转换如何与带符号字符和无符号int一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆