% * s C format specifier

printf("%d",printf("%*s%*s",6,"",6))

The results of adding two numbers (6 + 6), does anyone have such format specifiers

+4
source share
3 answers

In your example, it is wrong, the argument is nested printf .

If you write it like this:

 printf("%d",printf("%*s%*s",6,"",6, "")); 

if it seems to be normal. * means that the precision field should be read from the next argument in printf . Thus, in this case, the "nested" printf prints two lines with a length of not more than 6.

Since printf returns the number of characters written, internal printf returns 12, which prints to external printf .

Quote from the relevant part of the manual page:

Accuracy

Optional precision in the form of a period ('.') Followed by an optional decimal digit. Instead of a decimal digit string, you can write "*" or "* m $" (for some decimal integer m) to indicate that the precision is indicated in the next argument or in the mth argument, respectively, which should be of type int. If the precision is specified as ".", Or the precision is negative, the precision is assumed to be zero. This gives the minimum number of digits for d, i, o, u, x and X conversions, the number of digits that should appear after the radix symbol for a, A, e, E, f and F, version, the maximum number of significant digits for conversions g and G or the maximum number of characters that must be printed from a string for s and S.

I'm not sure how portable this is, but I'm sure there are much better ways to add two numbers .

+9
source

A * because the width specifier indicates that the width is passed as a parameter.

 printf("%*s%*s", 6, "", 6, ""); 

is equivalent to:

 printf("%6s%6s", "", ""); 

This will print 12 spaces.

Since printf returns the number of characters printed, it will return 12.

The final parameter "" is missing in the source code. If it works, it happens just by accident.

+1
source

printf returns the number of characters printed. The rest should be obvious.

-1
source

Source: https://habr.com/ru/post/1380993/


All Articles