c – %d for unsigned integer

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 signed 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.

Read more here: Source link