6

printf("%*d",variable);


I wants to know that what is the use of (*) in printf function

1

2 Answers 2

10

The star is used to specify the width of the value and printf takes then 3 arguments :

printf("%*d", width, value);

Example :

printf("%*d", 3, 16);

// output : " 16" (a space is added by printf to respect the specified width)

1

Reference

. followed by integer number or *, or neither that specifies precision of the conversion. In the case when * is used, the precision is specified by an additional argument of type int. If the value of this argument is negative, it is ignored. If neither a number nor * is used, the precision is taken as zero. See the table below for exact effects of precision.

For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.

 printf ("Width trick: %*d \n", 5, 10)

output

Width trick:    10
1
  • From what I've seen, if the argument is negative it takes its absolute value. (tested in GNU compilers) try this or this
    – WENDYN
    Commented Jun 19, 2020 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.