unsigned short and signed short comparison wierd behavior

不打扰是莪最后的温柔 提交于 2020-01-11 04:02:05

问题


When I assign the same value to signed and unsigned short and do a comparison it fails but it works with int. Unless I cast one or the other to make them same types the comparison is not working.

#include<stdio.h>

int main()
{
    signed short b = -10;
    unsigned short  c=-10;
    signed int a = -10;
    unsigned int d=-10;

    printf("%d , %d\n",b,(unsigned short)b);
    printf("%d , %d\n",(signed short)c,c);
    printf("%d , %u\n",a,(unsigned int)a);
    printf("%d , %u\n",(signed int )d,d);
    printf("b==c %d\n", b==c);
    printf("a==d %d\n", a==d);
    return 0;
}

Output:

./a.out
-10 , 65526
-10 , 65526
-10 , 4294967286
-10 , 4294967286
b==c 0
a==d 1

I ran this in sun solaris sparc and hpux itanium with same output. (64 bit exes)


回答1:


This is because of the integer promotions rules of C.

Here is what's going on: when you try comparing two variables of different types, the compiler checks if each type can be promoted to an int. A type can be promoted to int when all its possible values fit into an int. If a type can be promoted to an int, it is promoted to an int; otherwise, the compiler checks if it can promote the type to an unsigned int. If this promotion is possible, the value is promoted to unsigned int before proceeding with the comparison.

In your first example both signed short and unsigned short can be promoted to an int. Once this is done, your get different values, so the comparison returns false.

In your second example, however, no promotions are done, because int cannot hold all values of unsigned int and vice versa. The "raw" comparison is performed, which compares the same representations and returns true.



来源:https://stackoverflow.com/questions/25811220/unsigned-short-and-signed-short-comparison-wierd-behavior

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