Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf gives unexpected result

Tags:

c

I was wondering why the outcome of this program is 5621?

#include <stdio.h>

main()
{
    int i=56;
    printf("%d\n",printf("%d",printf("%d",i)));
    getch();
}
like image 216
C_Intermediate_Learner Avatar asked Jul 23 '13 16:07

C_Intermediate_Learner


People also ask

What to use instead of printf in C?

puts() '. It moves the cursor to the next line. Implementation of puts() is easier than printf().

What is the difference between printf() and puts()?

the printf() function is used to print both strings and variables to the screen while the puts() function only permits you to print a string only to your screen.

Can I use puts instead of printf?

puts() vs printf() for printing a stringputs() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler than printf()), and if the string has formatting characters like '%s', then printf() would give unexpected results.

What does printf return?

The fprintf() , printf() , and sprintf() functions return the number of characters output, or a negative value if an output error occurs.


1 Answers

printf returns the amount of characters it has printed.

So first the most inner printf gets called with 56, printing 56. Then it returns the amount of characters it has printed (2) to the middle printf, printing 2. Then finally the amount of characters printed (1) gets passed into the outer printf, which then gets printed to procude 5621.

like image 128
orlp Avatar answered Nov 09 '22 00:11

orlp