简体   繁体   中英

Question : char d = -1 printf(“%u”,d); why outpt is not 255

I confused about first "printf" function print d is not 255, why d is 4294967295, anyone can help me explain that

#include <stdio.h>

int main()
{
    unsigned char c = -1;
    char d = -1;
    int i = -1;
    printf("c=%u,d=%u,i=%u\n", c, d, i);
    printf("c=%d,d=%d,i=%d\n", c, d, i);
    return 0;
}

output is

在此处输入图片说明

The likely sequence of events in your C implementation is:

  • In unsigned char c = -1; , -1 is converted to unsigned char , producing 255, and c is initialized to this value.
  • char is signed in the C implementation you are using, so char d = -1; initializes d to −1.
  • int i = -1; of course initializes i to −1.
  • In printf("c=%u,d=%u,i=%u\\n", c, d, i); , the unsigned char and char values of c and d are automatically promoted to int , and you pass the values 255, −1, and −1 to printf .
  • The bits that represent these int values 255 (24 zeros and eight ones), −1 (32 ones), and −1 (32 ones) are passed to printf , but your %u conversion specifiers tell printf to expect unsigned int values. printf responds by interpreting these bits as if they were unsigned int .
  • In unsigned int in your C implementation, 24 zero bits followed by eight one bits represents 255, so printf prints that for the first conversion.
  • 32 one bits represents 4294967295, so printf prints that for the second and third conversion.
  • In printf("c=%d,d=%d,i=%d\\n", c, d, i); , all the arguments after the format string are int after automatic promotion, and %d tells printf to expect int , so everything works as expected, and printf prints 255, −1, and −1.

Because your argument types in the first printf do not match the conversion specifiers, the C standard does not define the resulting behavior. Although the above is likely what happened in your C implementation, the C standard does not guarantee this will happen in other C implementations or even in other programs doing this in this C implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM