Coming from a typeless language (PHP) I’m a bit confused about datatypes in C. I’m facing the following strange behavior.
//First case
unsigned int a;
a = -1;
printf("a = %u", a); //Outputs a strange number, no problem here
//Second case
unsigned int a;
a = -1;
printf("a = %d", a); //Outputs -1
What I don’t understand is how a “contained” a signed value after we specifically said it’s unsigned?
How can only formatting the output in the second case do that?
The
-1will be represented as something like10000000 00000000 00000000 00000001(ifinthas 4 bytes as in my case). When you are outputting it with%d, theprintf()interprets it as a normal int, thus it interprets the leading1as the sign, and prints-1. If you output it as%u,printf()knows it’s unsigned, and interprets the leading1as2^32, resulting in4294967295as output.