 # How does it print -11?

#include<stdio.h>
#include<limits.h>
int main(){
unsigned int a=10;
a=~a;
printf("%d\n",a);
return 0;
}

1 Like

Since int is of 32 bits, 10 is stored as 28 bits of 0s followed by 1010. The leftmost bit is the sign bit, 1 for negative.

Now, complementing it will turn the first 28 bits to 1, followed by 0101. Now sign bit is 1 so the compiler will treat the number as negative. So, it will apply 2’s complement to the number i.e. complementing and adding 1 to it.

So, complementing will result in first 28 bits set to 0, then 1010. Now, adding 1 to it becomes 1011 i.e. 11. Since, sign bit was set, so it will store and print -11.

2 Likes

The format specifier for unsigned int is %u. But you put %d, hence an unsigned integer is being treated as signed integer and hence the corresponding value (-11, as explained by @bal_95 ) is printed. I am sure you should have received warnings when you compiled. Something like this, format specifier %d expects int, but unsigned integer is provided…

2 Likes