Search code examples
cunsigned

How is unsigned int variable able to store negative value?


When i tried the below code snippet, its printing -1 as output. But how unsigned int is storing -1?

code:

unsigned int a = -1;
printf("a = %d \n",a)

The output: -1

How is this possible?

note: I saw similar question in stackoverflow. This is different. My question is why it printed -1 as output even though "a" is unsigned.


Solution

  • The %d specifier tells printf, "Interpret this value as a signed integer". Even though a has a value of 0xFFFFFFFF (4,294,967,296), when interpreted as a signed value, it will show up as -1.