Nested printf (printf inside printf) in C

Predict the output of the following C program with a printf inside printf.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<stdio.h>
   
int main()
{
   int x = 1987;
   printf("%d", printf("%d", printf("%d", x)));
   return(0);
}

chevron_right


Output :

198741

Explanation :
1. Firstly, the innermost printf is executed which results in printing 1987



2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces to :

filter_none

edit
close

play_arrow

link
brightness_4
code

printf("%d", printf("%d", 4));

chevron_right


3. The second printf then prints 4 and returns the total number of digits in 4 i.e 1 (4 is single digit number ).

4. Finally, the whole statement simply reduces to :

filter_none

edit
close

play_arrow

link
brightness_4
code

printf("%d", 1);

chevron_right


5. It simply prints 1 and output will be :

Output:

198741

So, when multiple printf’s appear inside another printf, the inner printf prints its output and returns length of the string printed on the screen to the outer printf.

This article is contributed by Rishav Raj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


10


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.