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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With