Search code examples
cindexingprintfformat-specifiers

Index specification in printf format specifier


In the following program, printf() function print according to argument index specification.

#include <stdio.h>

int main()
{
        printf("%3$d  %4$f  %2$d  %1$d\n", 1,  2,  3,  4.5);
}

Output:

3  4.500000  2  1

So, I have question, Is it valid for any compiler or support only GCC compiler?


Solution

  • As you suspect, numbered argument conversion specifications (that is, n$) are not required by the C standard. But they are not idiosyncratic to the Gnu implementation; they are required by the POSIX standard (specification here) and have been since at least the 1997 version 2.

    Most Unix and unix-like implementations feature some measure of Posix compliance, and numbered argument specifications are not a recent addition. So you will likely find support in most current Unix and Unix-like platforms, including any which use the Gnu standard C library (Linux) or the FreeBSD standard C library (Mac OS X). However, the (native) Windows C standard library (which is not Posix-compliant) only provides support for numbered argument specifications if you use the *printf_p family of functions. See here and here.)