Which integral promotions do take place when printing a char?

后端 未结 3 1382
深忆病人
深忆病人 2021-01-11 15:15

I recently read that

unsigned char x=1;
printf(\"%u\",x);

invokes undefined behaviour since due to the format specifier %u, printf expects

3条回答
  •  一向
    一向 (楼主)
    2021-01-11 16:00

    Since printf uses a variable argument list, the integer promotions are applied to its integer arguments. In any normal C implementation, the integer promotions convert an unsigned char to an int. Then you are formatting an int With a specifier for unsigned int, so the behavior is undefined.

    There is no conflict between saying that a character may be used where an integer may be used and the fact that your statement has behavior not defined by the C standard. Although you may use a character in place of an integer, the rules about what may be printed with %u still apply. If using a character results in an integer appropriate for the specifier, the behavior is defined. If using a character results in an integer inappropriate for the specifier, the behavior is not defined by the C standard.

    Discussion elsewhere on Stack Overflow concluded that an exotic C implementation might in theory conform to the C standard while having char types (plain, signed, and unsigned) as wide as int types. In such an implementation, and int could not represent all values of an unsigned char, so an unsigned char would have to be promoted to an unsigned int. However, such an implementation would be exotic and troublesome (notably with handling EOF), and you may ignore it in practice.

提交回复
热议问题