By man
I find
printf("%*d", width, num);
and
printf("%2$*1$d", width, num);
are equivalent.
But IMO the second style should be the same as:
printf("%*d", num, width);
However via testing it seems man
is right; why?
I agree that the man page is confusing because it explains two concepts (length modifier as positional argument) in one example, so I go to the mighty couple
vi
/gcc
:test.c
Compiling will give warnings if not all arguments are used:
But then here you see the result:
So the
1$
applies to the asterisk, therefore the first argument is the width. The2$
applies to the entire format specification, therefore the second argument is the one whose value will be printed.In your second example:
The first number, 2, is attached to the format specifier, and the second number, 1, is attached to the
*
. If you read the documentation forprintf
, this is clear. Nothing unusual is happening.The relevant part of the POSIX specification of
printf()
defines this behaviour:The
%n$
identifies the argument whose value is to be printed - argument 2 in your example.The
*n$
identifies the argument whose value is to be treated as the format width - argument 1 in your example.So, those writing the manual followed the standard.
You argue in a comment:
As noted already, the standard clearly attaches the
n$
parts as postfix modifiers of%
and*
, rather than as prefix modifiers of the format conversion specifier (d
in this example) and*
. Your putative design could, probably, be made to work, but was not the design chosen.