Reputation: 1142
I was searching for how to add two numbers without using ('+'/'++') and went through link. But, I also found this solution:
#include<stdio.h>
int add(int x, int y);
int add(int x, int y)
{
return printf("%*c%*c", x, ' ', y, ' ');
}
int main()
{
printf("Sum = %d", add(3, 4));
return 0;
}
Can somebody explain what's happening in add function?
Upvotes: 1
Views: 905
Reputation: 62469
Well what happens is this: the *
before c
tells printf
that:
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
Hence this means that the first space character will be printed with a width of a
and the second one with a width of b
. At the same time printf
returns the number of characters printed, which is actually a + b
characters.
Upvotes: 1
Reputation: 183978
return printf("%*c%*c", x, ' ', y, ' ');
The *
in the printf
format means that the field width used to print the character is taken from an argument of printf
, in this case, x
and y
. The return value of printf
is the number of characters printed. So it's printing one ' '
with a field-width of x
, and one with a field-width of y
, makes x + y
characters in total.
Upvotes: 2