I recently read that
unsigned char x=1;
printf("%u",x);
invokes undefined behaviour since due to the format specifier %u, printf expects an unsigned int. But still I would like to understand what is going on in this example.
I think that the integral promotion rules apply with the expression printf("%u",x)
and the value represented by x
.
A.6.1 Integral Promotion
A character, a short integer, or an integer bit-field, all either signed or not, or an object of enumeration type, may be used in an expression wherever an integer may be used. If an int can represent all the values of the original type, then the value is converted to int; otherwise the value is converted to unsigned int. This process is called integral promotion.
What does "may be used" mean here? Does it mean 'is syntactically correct' or 'is defined behaviour'?
And how is x promoted in this example? I have read that it is promoted to an int, but if printf("%u", (int x))
is still undefined behaviour then I don't really understand why...