gpt4 book ai didi

c - printf 的 h 和 hh 修饰符的用途是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:00 34 4
gpt4 key购买 nike

除了 %hn%hhn(其中 hhh 指定 < em>指向对象),printf 格式说明符的hhh 修饰符有什么意义?

由于标准要求默认提升应用于可变参数函数,因此不可能传递类型为 charshort(或任何有符号/其未签名的变体)到 printf

根据 7.19.6.1(7),h 修饰符:

Specifies that a following d, i, o, u, x, or X conversion specifier applies to a short int or unsigned short int argument (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); or that a following n conversion specifier applies to a pointer to a short int argument.

如果参数实际上是 shortunsigned short 类型,则提升为 int,然后转换回 short unsigned short 将产生与提升为 int 相同的,而无需任何返回转换。因此,对于 shortunsigned short 类型的参数,%d%u 等应该给出相同的结果为 %hd%hu 等(同样适用于 char 类型和 hh)。

据我所知,hhh 修饰符可能有用的唯一情况是参数将其传递给 int 超出 shortunsigned short 的范围,例如

printf("%hu", 0x10000);

但我的理解是,像这样传递错误的类型无论如何都会导致未定义的行为,因此您不能期望它打印 0。

我见过的一个真实案例是这样的代码:

char c = 0xf0;
printf("%hhx", c);

作者希望它打印 f0,尽管实现有一个带符号的普通 char 类型(在这种情况下,printf("%x", c) 将打印 fffffff0 或类似内容)。但这种期望是否合理?

(注意:原来的类型是 char,它被提升为 int 并转换回 unsigned char char,从而改变打印的值。但是标准是否指定了这种行为,或者它是损坏的软件可能依赖的实现细节?)

最佳答案

一个可能的原因:为了在格式化输入函数中使用那些修饰符的对称性?我知道这不是绝对必要的,但也许可以看到它的值(value)?

虽然他们没有在 the C99 Rationale document 中提及对称性对于修饰符“h”和“hh”的重要性,委员会确实提到它作为为什么 fscanf() 支持“%p”转换说明符的考虑因素(尽管这对于 C99 来说不是新的 - C90 中支持“%p” ):

Input pointer conversion with %p was added to C89, although it is obviously risky, for symmetry with fprintf.

在关于 fprintf() 的部分中,C99 基本原理文档确实讨论了添加了“hh”,但只是让读者引用 fscanf() 部分:

The %hh and %ll length modifiers were added in C99 (see §7.19.6.2).

我知道这是一个脆弱的线索,但我还是在猜测,所以我想我会给出可能存在的任何论据。

此外,为了完整起见,“h”修饰符出现在原始的 C89 标准中 - 即使由于广泛使用而并非绝对必要,即使可能没有技术要求,它也会存在使用修饰符。

关于c - printf 的 h 和 hh 修饰符的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521817/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com