Home > Net >  %d for unsigned integer
%d for unsigned integer

Time:10-01

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;
}

CodePudding user response:

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.

CodePudding user response:

refer to printf() manual, they said:

A character that specifies the type of conversion to be applied. The conversion specifiers and their meanings are:

d, i

The int argument is converted to signed decimal notation. The precision, if any, gives the minimum number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with zeros. The default precision is 1. When 0 is printed with an explicit precision 0, the output is empty.

so it means that the parameter even if it's in unsigned representation, it will be converted into its signed int representation and printed, see the following code example:

#include <stdio.h>

int main(){
    signed int x1 = -2147483648;
    unsigned int x2 = -2147483648;
    unsigned long long x3 = -2147483648;

    printf("signed int x1 = %d\n", x1);
    printf("unsigned int x2 = %d\n", x2);
    printf("signed long long x3 = %d\n", x3);
}

and this is the output:

signed int x1 = -2147483648
unsigned int x2 = -2147483648
signed long long x3 = -2147483648

so it means no matter what is the type of the variable printed, as long as you specified %d as format specifier, the variable will be converted into its representation in unsigned int and be printed

in case of unsigned char like for example:

#include <stdio.h>

int main(){
    unsigned char s = -10;

    printf("s = %d",s);
}

the output is :

s = 246

as the binary representation of unsigned char s = -10 is :

1111 0110

where the MSB bit is 1, but when it's converted into signed int, the new representation is :

0000 0000 0000 0000 0000 0000 1111 0110

so the MSB is no longer have that 1 bit in its MSB which represents whether the number is positive or negative.

  • Related