Search code examples
cunsigned-integer

%d for unsigned integer


I accidentally used "%d" to print an unsigned integer using an online compiler. I thought errors would pop out, but my program can run successfully. It's good that my codes are working, but I just don't understand why.

#include <stdio.h>

int main() {
    unsigned int x = 1;

    printf( "%d", x);

    return 0;
}

Solution

  • The value of the "unsigned integer" was small enough that the MSB (most significant bit) was not set. If it were, printf() would have treated the value as a "negative signed integer" value.

    int main() {
        uint32_t x = 0x5;
        uint32_t y = 0xC0000000;
    
        printf( "%d  %u  %d\n", x, y, y );
    
        return 0;
    }
    
    5  3221225472  -1073741824
    
    

    You can see the difference.

    With new-fangled compilers that "read into" printf format specifiers and match those with the datatypes of following parameters, it may be that the online compiler may-or-may-not have been able to report this type mismatch with a warning. This may be something you will want to look into.