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)
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 toint
when all its possible values fit into anint
. If a type can be promoted to anint
, it is promoted to anint
; otherwise, the compiler checks if it can promote the type to anunsigned int
. If this promotion is possible, the value is promoted tounsigned int
before proceeding with the comparison.In your first example both
signed short
andunsigned short
can be promoted to anint
. Once this is done, your get different values, so the comparison returnsfalse
.In your second example, however, no promotions are done, because
int
cannot hold all values ofunsigned int
and vice versa. The "raw" comparison is performed, which compares the same representations and returnstrue
.