`printf()` 中格式说明符“%qd”的用途是什么?

What is the purpose of format specifier "%qd" in `printf()`?

我在浏览 github 代码时看到格式说明符 %qd。然后我检查了 GCC 编译器,它工作正常。

#include <stdio.h>

int main()
{  
    long long num = 1;
    printf("%qd\n", num);
    return 0;
}

printf() 中格式说明符 %qd 的用途是什么?

q 表示 printf 函数中的 quad word 格式说明符,用于在所有机器上轻松处理 64 位

来自Wikipedia

Additionally, several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions:

q - For integer types, causes printf to expect a 64-bit (quad word) integer argument. Commonly found in BSD platforms

%qd was intended to handle 64 bits comfortably on all machines, and was originally a bsd-ism (quad_t).

However, egcs (and gcc before that) treats it as equivalent to ll, which is not always equivalent: openbsd-alpha is configured so that long is 64 bits, and hence quad_t is typedef'ed to long. In that particular case, the printf-like attribute doesn't work as intended.

If sizeof(long long) == sizeof(long) on openbsd-alpha, it should work anyway - i.e. %ld, %lld, and %qd should be interchangeable. On OpenBSD/alpha, sizeof(long) == sizeof(long long) == 8.

在广泛使用 ISO C99 扩展之前,出现了几个特定于平台的长度选项,q 就是其中之一。它用于整数类型,这导致 printf 期望 64 位(四字)整数参数。它常见于 BSD 平台。

然而,C99 和 C11 都没有提及长度修饰符 qfprintf() 的 macOS (BSD) 手册页将 q 标记为已弃用。因此,建议使用 ll 而不是 q

参考文献:

https://gcc.gnu.org/ml/gcc-bugs/1999-02n/msg00166.html

https://en.wikipedia.org/wiki/Printf_format_string

https://port70.net/~nsz/c/c11/n1570.html#7.21.6.1p7

最有趣的 C 语言相关问题之一。符号文字 “%qd” 表示为四字,在 C 编程语言中指定用于有效处理 64 位的 printf 函数。还要记住,从 1999 版的 C 标准开始,sizeof(long long) >= sizeof(long) 就可以推断出 long long 的范围至少有 64 位。