Question

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
Was it helpful?

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

OTHER TIPS

When passed to printf (or similar functions), %*c means you're passing two parameters instead of one. The first parameter specifies a field width, and the second a character (or string, int, etc.) to write out in that width of field.

printf returns the total number of characters written to the output stream.

A number after % specifies the field width; so %5c will print 4 spaces, followed by the character argument, giving a total of 5 characters.

* specifies that the field width is provided as an argument to printf. So this will print one field of x characters, followed by another of y characters. Each field consists of spaces followed by a carriage-return ('\r'), so there shouldn't be any visible output. printf returns the total number of characters printed - in this case, x+y.

i agree with leeduhem, it is extremely clever,

printf() return the number of character it printed. For the argument, I think it is more easy to understand with an example:(Also you can see the width trick in here:

#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

int main() {
    // your code goes here
    int x = printf("%*c", 100, '\r');
    printf("%d\n", x);
    return 0;
}

x is whatever value you set to specific the width (in the eg, it's 100)

That means the width you specific is actually counted and return by the printf()

But I think this add() can only duel with positive numbers, if one of the number is <= 0, the method should fail, you may try add(-3,-4), in my own machine it still print 7...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top