Search code examples
cprintfformat-specifiers

How does calling printf() add numbers here?


I don't understand how this printf() call is working to add together two numbers. Does the %*c have something to do with it?

//function that returns the value of adding two number
int add(int x, int y)
{
    NSLog(@"%*c",x, '\r');
    NSLog(@"%*c",y, '\r');
    return printf("%*c%*c",  x, '\r',  y, '\r'); // need to know detail view how its working
}

for calling

printf("Sum = %d", add(3, 4));

Output

Sum=7

Solution

  • Oh, this is clever.

    return printf("%*c%*c",  x, '\r',  y, '\r');
    

    On success, printf() will return how many character it printed, and "%*c", x, '\r' tell it to print x characters (x-1 spaces followed by one \r). Therefore, printf("%*c%*c", x, '\r', y, '\r') will return how many characters are printed, which is x+y.

    See printf(3) for further details.


    Note:

    As pointed out by @shole, this int add(int x, int y) works only for both x and y are nonnegative integers. For example:

    add(-1, 1) // gives 2 instead of 0
    add(0, 1)  // gives 2 instead of 1