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

青春壹個敷衍的年華 提交于 2019-12-05 09:58:56

问题


I saw format specifier %qd when browsing github code. Then I checked in GCC compiler, it's working fine.

#include <stdio.h>

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

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


回答1:


Though only a few articles come about %qd in a normal google search, for future reference, this answer is the compilation of my own research, rsp's answer and little discussions here in the comments section by Jonathan Leffler and StoryTeller.

%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.

Several platform-specific length options came to exist prior to widespread use of the ISO C99 extensions, q was one of them. It was used for integer types, which causes printf to expect a 64-bit (quad word) integer argument. It is commonly found in BSD platforms.

However, both of the C99 and C11 says nothing about length modifier q. The macOS (BSD) manual page for fprintf() marks q as deprecated. So, using ll is recommended in stead of q.

References:

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




回答2:


q means quad word format specifier in printf function which is used to handle 64 bits comfortably on all machines.

From 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




回答3:


One of most interesting C language related question to answer. The symbolic literal “%qd” represent as quad word, which is specified as used to handle 64 bits effectively with the printf function in the C programming language. Also just remember that, from 1999 edition of the C standard states that sizeof(long long) >= sizeof(long), and one can infer that the range of long long has a size of at least 64 bits.



来源:https://stackoverflow.com/questions/50830312/what-is-the-purpose-of-format-specifier-qd-in-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!