on net: using printf
to add two numbers(without using any operator) like following:
main()
{
printf("Summ = %d",add(10,20))
return 0;
}
int add(int x,int y)
{
return printf("%*d%*d",x,' ',y,' ');
}
Could anyone please explain, how this works:
return printf("%*d%*d",x,' ',y,' ');
Note: This fails when i call "sum" like following:
sum(1,1) or sum(3,-1)
There are two central concepts here:
printf()
returns the number of characters printed.%*d
format specifier causes printf()
to read two integers from its arguments, and use the first to set the field width used to format the second (as a decimal number).So in effect the values being added are used as field widths, and printf()
then returns the sum.
I'm not sure about the actual d
formatting of the space character, at the moment. That looks weird, I would have gone with an empty string instead:
static int sum(unsigned int a, unsigned int b)
{
return printf("%*s%*s", a, "", b, "");
}
int main(void)
{
unsigned int a = 13, b = 6;
int apb = sum(a, b);
printf("%d + %d = %d?\n", a, b, apb);
return 0;
}
The above works and properly computes the sum as 19
.
printf
returns the number of printed characters.
Here, it is used in the add
function to generate a string only composed of 10
+ 20
spaces, by using the format string.
So the printf
in the add
function will return 30
.
Then, this result is simply printed with printf (his main purpose).
Note: it might be evident, but this printf
usage has to be avoided. It's very dirty as it generates useless outputs. Imagine: add(10000,10000)
...
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