How implicit conversion work with signed character and unsigned int? [duplicate]

淺唱寂寞╮ 提交于 2019-12-08 14:20:06

问题


#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

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...


回答1:


I expected the output to be x == y as during comparison signed character is supposed to be converted to unsigned int?

Well, you're halfway there.

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.

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.

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);

and

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

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

  • If you want to print a signed char value, use %hhd
  • If you want to print an unsigned int, use %u


来源:https://stackoverflow.com/questions/47528611/how-implicit-conversion-work-with-signed-character-and-unsigned-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!