(GCC) Dollar sign in printf format string

前端 未结 2 2116
清酒与你
清酒与你 2020-12-15 18:27

I\'ve seen the following line in a source code written in C:

printf(\"%2$d %1$d\", a, b);

What does it mean?

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 18:56

    Per the C spec C11dr 7.21.6.1

    As part of a print format, the first % in "%2$d %1$d" introduces a directive. This directive may have various flags, width, precision, length modifier and finally a conversion specifier. In this case 2 is a width. The next character $ is neither a precision, length modifier nor conversion specifier. Thus since the conversion specification is invalid,

    ... the behavior is undefined. C11dr 7.21.6.1 9

    The C spec discusses future library directions. Lower case letters may be added in the future and other characters may be used in extensions. Of course $ is not a lower case letter, so that is good for the future. It certainly fits the "other character" role as $ is not even part of the C character set.

    In various *nix implementations, $ is used as describe in Linux Programmer's Manual PRINTF(3). The $, along with the preceding integer defines the argument index of the width.

提交回复
热议问题