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?

5
  • 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! Commented Oct 6, 2012 at 11:11
  • Can you use other operators (e.g. - / *)? Commented Oct 6, 2012 at 12:13
  • This was asked on stackoverflow before, but I'm unable to find it. Does anyone remember this one? Commented Oct 6, 2012 at 12:13
  • No, I can't use any other operators. Commented Oct 6, 2012 at 12:49
  • Possible duplicate of How to add two numbers without using ++ or + or another arithmetic operator Commented Jan 16, 2016 at 11:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Then this means that first %*c takes first ' ' character to print it x times? Am i right?
Yes and no. In the case of ' ' that's what it does, but the correct description is that it pads whatever character it shall print with spaces to fill the required field-width.
And are these spaces padded before or after the character which is to be printed?
@Vaibhav Agarwal: Just put a - for example instead of space and see the printout. For me the padding is at the front.
Padding is usually added on the left, but with a - flag, the field is left-justified and the padding added on the right.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.