I understand that I am assigning signed int a value that is larger than what it can handle. Also I should be using %d
for signed and %u
for unsigned. Similarly I should not be assigning -ve
value to unsigned. But if I make such assignments and use printf as below, I get the results show below.
My understanding is that in each case, the number of converted to its two's compliment binary representation which is same for -1
or 4294967295
. That is why %u
for signed prints 4294967295
by ignoring -ve
leftmost bit. When used %d for signed int, it uses left most bit as -ve
flag and prints -1
. Similarly %u
for unsigned prints unsigned value but %d
causes it to treat the number as signed and thus prints -1
. Is that correct?
signed int si = 4294967295;
unsigned int ui = 4294967295;
printf("si = u=%u d=%d\n", si, si);
printf("ui = u=%u d=%d\n", ui, ui);
Output:
si = u=4294967295 d=-1
ui = u=4294967295 d=-1
signed int si = -1;
unsigned int ui = -1;
printf("si = u=%u d=%d\n", si, si);
printf("ui = u=%u d=%d\n", ui, ui);
Output:
si = u=4294967295 d=-1
ui = u=4294967295 d=-1
-1
to an unsigned value is always well defined behavior. – Shafik Yaghmourunsigned
integral value is not well-defined. Just as re-interpreting a too-bigunsigned
integral value as asigned
integral value is not. – Deduplicator