Say I want to print unsigned char
:
unsigned char x = 12;
which is correct. This:
printf("%d",x);
or this:
printf("%u",x);
?
The thing is elsewhere on SO I encountered such discussion:
-Even with ch changed to unsigned char, the behavior of the code is not defined by the C standard. This is because the unsigned char is promoted to an int (in normal C implementations), so an int is passed to printf for the specifier %u. However, %u expects an unsigned int, so the types do not match, and the C standard does not define the behavior
-Your comment is incorrect. The C11 standard states that the conversion specifier must be of the same type as the function argument itself, not the promoted type. This point is also specifically addressed in the description of the hh length modifier: "the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing"
So which is correct? Any reliable source saying on this matter? (In that sense we should also print unsigned short
int with %d because it can be promoted to int
?).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…