Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addition using printf in C [duplicate]

Tags:

c

math

printf

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) 
like image 286
bapi Avatar asked Aug 26 '13 13:08

bapi


2 Answers

There are two central concepts here:

  1. printf() returns the number of characters printed.
  2. The %*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.

like image 95
unwind Avatar answered Sep 19 '22 12:09

unwind


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

like image 27
aymericbeaumet Avatar answered Sep 21 '22 12:09

aymericbeaumet