Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()?

like image 694
msc Avatar asked Jun 13 '18 06:06

msc


People also ask

What is the meaning of %U in printf () statement?

An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables. Syntax: printf(“%u”, variable_name);

What is the purpose of %c format specifier?

The %c format specifier is implemented for representing characters. It is used with the printf() function for printing the character stored in a variable. You should incorporate the %c format specifier when you want to print character data.

What is %B in printf?

The Printf module API details the type conversion flags, among them: %B: convert a boolean argument to the string true or false %b: convert a boolean argument (deprecated; do not use in new programs).


2 Answers

%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

like image 79
UkFLSUI Avatar answered Nov 05 '22 01:11

UkFLSUI


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

like image 38
msc Avatar answered Nov 05 '22 01:11

msc