1

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?

Community
  • 1
  • 1
Vaibhav Agarwal
  • 1,124
  • 4
  • 16
  • 25
  • 1
    If you have a C99 implementation you can instead do: `return snprintf(NULL, 0, "%*c%*c", x, '#', y, '#');` and not mess up the output. Anyway, this method will never work with negative values! – pmg Oct 06 '12 at 11:11
  • Can you use other operators (e.g. - / *)? – lashgar Oct 06 '12 at 12:13
  • This was asked on stackoverflow before, but I'm unable to find it. Does anyone remember this one? – stefan Oct 06 '12 at 12:13
  • No, I can't use any other operators. – Vaibhav Agarwal Oct 06 '12 at 12:49
  • Possible duplicate of [How to add two numbers without using ++ or + or another arithmetic operator](http://stackoverflow.com/questions/1149929/how-to-add-two-numbers-without-using-or-or-another-arithmetic-operator) – Box Box Box Box Jan 16 '16 at 11:12

2 Answers2

2
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.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

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.

Tudor
  • 61,523
  • 12
  • 102
  • 142