I recently read that
unsigned char x=1;
printf(\"%u\",x);
invokes undefined behaviour since due to the format specifier %u, printf expects
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.