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;
}
@powersource97, %. *s means you are reading the precision value from an argument, and precision is the maximum number of characters to be printed, and %*s you are reading the width value from an argument, which is the minimum number os characters to be printed. – Vargas. Sep 24, 2021 at 20:50.
The %*d in a printf allows you to use a variable to control the field width, along the lines of: int wid = 4; printf ("%*d\n", wid, 42);
%s and string We can print the string using %s format specifier in printf function. It will print the string from the given starting address to the null '\0' character. String name itself the starting address of the string. So, if we give string name it will print the entire string.
Example 1: C Output The printf() is a library function to send formatted output to the screen. The function prints the string inside quotations. To use printf() in our program, we need to include stdio.h header file using the #include <stdio.h> statement.
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
N
, or-
before the *
, e.g. %-*s
, or%-12s
, %-6d
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With