It all has to do with interpretation of the value.
If you assume 16 bit signed and unsigned integers, then here some examples that aren't exactly correct, but demonstrate the concept.
0000 0000 0000 1100 unsigned int, and signed int value 12
1000 0000 0000 1100 signed int value -12, and a large unsigned integer.
For signed integers, the bit on the left is the sign bit.
0 = positive
1 = negative
For unsigned integers, there is no sign bit.
the left hand bit, lets you store a larger number instead.
So the reason you are not seeing what you are expecting is that.
unsigned int x = -12, takes -12 as an integer, and stores it into x. x is unsigned, so
what was a sign bit, is now a piece of the value.
printf lets you tell the compiler how you want a value to be displayed.
%d means display it as if it were a signed int.
%u means display it as if it were an unsigned int.
c lets you do this kind of stuff. You the programmer are in control.
Kind of like a firearm.
It's a tool.
You can use it correctly to deal with certain situations,
or incorrectly to remove one of your toes.
one possibly useful case is the following
unsigned int allBitsOn = -1;
That particular value sets all of the bits to 1
1111 1111 1111 1111
that can be useful sometimes.
printf
anint
(the"%d"
), but instead you give it anunsigned
. Don't lie to the compiler – pmg Mar 2 '11 at 15:37-12
converted to unsigned results in(UINT_MAX + 1) - 12
. – pmg Mar 2 '11 at 16:01-Wsign-conversion
(included in-Wconversion
) can be used to warn about this. As you now know it is not part of-Wall
or-Wextra
. – pmg Mar 2 '11 at 16:12-Wall
, since it doesn't turn on "all" warnings. – user541686 Mar 3 '11 at 7:49