unsigned short and signed short comparison wierd b

2019-02-15 18:35发布

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)

标签: c++ c 64bit
1条回答
smile是对你的礼貌
2楼-- · 2019-02-15 19:21

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.

查看更多
登录 后发表回答