Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this printf trick works

Tags:

c

printf

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?

like image 509
izac89 Avatar asked Dec 14 '18 12:12

izac89


1 Answers

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)

like image 118
Ivaylo Strandjev Avatar answered Oct 02 '22 04:10

Ivaylo Strandjev