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 stands for width. But what is the width and how does it turn out that the sum is obtained for the example below?

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

Perfect 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; } 
+5
source share
3 answers

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 there are only 9 characters.

In your published code, the function returns the result printf , which gives the number of characters printed, so 9. Basically you print this number 9.

+5
source

printf returns the number of characters printed.

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

In general, printf prints N - length_of_text spaces (if it is a number > 0 , zero spaces otherwise), followed by text. The same goes for numbers.

so

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

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

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

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

By default, printf is right-aligned (spaces in front of the text). To make it left aligned, either

  • enter negative N or
  • add - before * , for example. %-*s , or
  • the static version works, for example. %-12s , %-6d
+7
source

Everything is as expected. According to the manual

format
(optional). followed by an integer or *, or none of them indicates the accuracy of the conversion. When * is used, precision is indicated 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 assumed to be zero. See the table below for exact accuracy effects.

Return value
1-2) The number of characters written in case of a 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, x + y written as the number of spaces (including precision), which is the return value.

+1
source

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


All Articles