printf 一个文字数字(int),同时期望一个更短的数字

printf a literal number (int) while expecting a shorter number

假设我们有这行代码:

printf("%hi", 6);

让我们假设 sizeof(short) == 2sizeof(int) == 4

printf 期望 short,但得到的 int 更宽。这是未定义的行为吗?

%hhi相同。

当您使用 %hi 时,

printf() 实际上并不期望参数是 short。当您调用可变参数函数时,所有参数都经过 default argument promotion。在整数参数的情况下,这意味着整数提升,这意味着所有小于 int 的整数类型都转换为 intunsigned int.

如果相应的参数是一个文字,所需要的只是它是一个适合 short 的值,您实际上不必将其转换为 short

standard 7.21.6.1.7 节是这样解释的:

the argument will have been promoted according to the integer promotions, but its value shall be converted to short int or unsigned short int before printing