The following code:
unsigned int c2 = -1;
printf("c2 = %u\n", c2);
Will never print 255
. The table you are looking at is referring to an unsigned integer of 8 bits. An int
in C needs to be at least 16 bits in order to comply with the C standard (UINT_MAX
defined as 2^16-1 in paragraph §5.2.4.2.1, page 22 here). Therefore the value you will see is going to be a much larger number than 255. The most common implementations use 32 bits for an int
, and in that case you'll see 4294967295 (2^32 - 1).
You can check how many bits are used for any kind of variable on your system by doing sizeof(type_or_variable) * CHAR_BIT
(CHAR_BIT
is defined in limits.h
and represents the number of bits per byte, which is again most of the times 8).
The correct code to obtain 255
as output is:
unsigned char c = -1;
printf("c = %hhu\n", c);
Where the hh
prefix specifier means (from man 3 printf
):
hh: A following integer conversion corresponds to a signed char
or unsigned char
argument, or a following n
conversion corresponds to a pointer to a signed char
argument.
Anything else is just implementation defined or even worse undefined behavior.