5

Taken from here:

printf("%d", printf("%*s%*s",a,"\r",b,"\r") );

Will print the result of a+b.

How on earth does it work?

Community
  • 1
  • 1
user2162550
  • 3,540
  • 6
  • 23
  • 39

2 Answers2

7

What the second(inner) printf does is to print as many chars as a and then as many chars as b. printf returns the number of chars printed, thus the sum of a and b.

Now let's get a bit deeper printf("%*s", a, "\r") will print a string with width specified via a parameter(in this case a) - that is what the asterisk does. By default the string is left padded with spaces. Thus you will get a - 1 spaces followed by a carriage return char. Doing it twice: printf("%*s%*s",a,"\r",b,"\r") will first print a string with width fixed to the value of a and then a second string with width fixed to the value of b.

After that the outer printf will print the number corresponding to the number of chars printed by the inner printf, but we already know what that would be, don't we?

NOTE: as left padding can only add, will never remove chars, the code is in fact wrong for a = 0 or b = 0 (or negatives of course)

Ivaylo Strandjev
  • 64,309
  • 15
  • 111
  • 164
2

Since printf returns the character count in output, and the %*s specifier actually reads two arguments (an integer and a character) and prints the character indented (so n-1 spaces are printed before it), essentially the inner printf printed a+b \rs, and the outer printf printed that number.

uv_
  • 710
  • 2
  • 13
  • 25
  • `%*s` takes a number and a string, not a character, and formats the string by padding on the left with spaces to at least the width given by the number. – Eric Postpischil Dec 14 '18 at 12:57