int a = -534;
unsigned int b = (unsigned int)a;
printf("%d, %d", a, b);
prints -534, -534
Why is the typecast not taking place?
I expected it to be -534, 534
If I modify the code to
int a = -534;
unsigned int b = (unsigned int)a;
if(a < b)
printf("%d, %d", a, b);
its not printing anything… after all a is less than b??
First, you don’t need the cast: the value of
ais implicitly converted tounsigned intwith the assignment tob. So your statement is equivalent to:Now, an important property of
unsignedintegral types in C and C++ is that their values are always in the range [0, max], where max forunsigned intisUINT_MAX(it’s defined inlimits.h). If you assign a value that’s not in that range, it is converted to that range. So, if the value is negative, you addUINT_MAX+1repeatedly to make it in the range [0,UINT_MAX]. For your code above, it is as if we wrote:unsigned int b = (UINT_MAX + a) + 1. This is not equal to-a(534).Note that the above is true whether the underlying representation is in two’s complement, ones’ complement, or sign-magnitude (or any other exotic encoding). One can see that with something like:
On a typical two’s complement machine with a 4-byte
int,cis0xff, anduis0xffffffff. The compiler has to make sure that when value-1is assigned tou, it is converted to a value equal toUINT_MAX.Now going back to your code, the
printfformat string is wrong forb. You should use%u. When you do, you will find that it prints the value ofUINT_MAX - 534 + 1instead of534.When used in the comparison operator
<, sincebisunsigned int,ais also converted tounsigned int. This, given withb = a; earlier, means thata < bis false:aas anunsigned intis equal tob.Let’s say you have a ones’ complement machine, and you do:
Let’s say a
char(signed or unsigned) is 8-bits on that machine. Thencanducwill store the following values and bit-patterns:Note that the bit patterns of
canducare not the same. The compiler must make sure thatchas the value-1, anduchas the valueUCHAR_MAX, which is 255 on this machine.There are more details on my answer to a question here on SO.