Search code examples
cmemorycharunsignedinteger-promotion

Clarifications about unsigned type in C


Hi I'm currently learning C and there's something that I quite don't understand. First of all I was told that if I did this:

unsigned int c2 = -1;
printf("c2 = %u\n", c2);

It would output 255, according to this table:

table

But I get a weird result: c2 = 4294967295

Now what's weirder is that this works:

unsigned char c2 = -1;
printf("c2 = %d\n", c2);

But I don't understand because since a char is, well, a char why does it even print anything? Since the specifier here is %d and not %u as it should be for unsigned types.


Solution

  • In this declaration

    unsigned char c2 = -1;
    

    the internal representation of -1 is truncated to one byte and interpreted as unsigned char. That is all bits of the object c2 are set.

    In this call

    printf("c2 = %d\n", c2);
    

    the argument that has the type unsigned char is promoted to the type int preserving its value that is 255. This value is outputted as an integer.

    Is this declaration

    unsigned int c2 = -1;
    

    there is no truncation. The integer value -1 that usually occupies 4 bytes (according to the size of the type int) is interpreted as an unsigned value with all bits set.

    So in this call

    printf("c2 = %u\n", c2);
    

    there is outputted the maximum value of the type unsigned int. It is the maximum value because all bits in the internal representation are set. The conversion from signed integer type to a larger unsigned integer type preserve the sign propagating it to the width of the unsigned integer object.