Tharif
Tharif

Reputation: 13971

What is %*c%*c in `printf`?

When i use printf in %*c%*c in printf, it requires 4 values and also prints the sum of 4 and 5. I could not find a valid reason for this.

When researching, I found that %*c denotes the width. But what is width and how come the sum is derived for below example ?

printf("%*c%*c", 4, ' ', 5, ' ');

Ideone link

Code :

#include <stdio.h>

int add(int x, int y)
{
    return printf("%*c%*c",x,' ', y,' ');
}

int main()
{
    printf("%d",add(4,5));
    return 0;
}

Upvotes: 7

Views: 10563

Answers (3)

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28840

printf returns the number of characters printed.

printf("%*c", N, C); prints N-1 blanks followed by the character C.

More generally, printf prints N - length_of_text blanks (if that number is > 0, zero blanks otherwise) followed by the text. The same applies to numbers as well.

therefore

return printf("%*c%*c", x, ' ', y, ' ');

prints a space prefixed with x minus length_of_space other spaces (x-1), then does the same for y. That makes 4+5 spaces in your case. Then printf returns the total number of characters printed, 9.

printf("%d",add(4,5));

This printf prints the integer returned by the add() function, 9.

By default, printf is right-aligned (blanks before text). To make it left-aligned, either

  • give a negative N, or
  • add a - before the *, e.g. %-*s, or
  • the static version works as well, e.g. %-12s, %-6d

Upvotes: 8

luoluo
luoluo

Reputation: 5533

Everything is as expected. According to the manual

format
(optional) . 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.

Return value
1-2) Number of characters written if successful or negative value if an error occurred.

So in your case:

int add(int x, int y)
{
    return printf("%*c%*c",x,' ', y,' ');
    //              ^ x is for the first *, y for the second *
}

As a result, the x + y number of space(including the precision) written, which is the return value.

Upvotes: 1

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36401

printf("%*c%*c", 4, ' ', 5, ' '); prints a space in a field of size 4 followed by a space in a field of size 5. So a total of 9 chars.

In your posted code, the function returns the result of printf which gives the number of printed chars, so 9. In main you then print this number 9.

Upvotes: 6

Related Questions