Addition using printf in C

c, math, printf

Solution

There are two central concepts here:

- `printf()` returns the number of characters printed.

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

Problem

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

Original source

Related problems