C_Intermediate_Learner
C_Intermediate_Learner

Reputation: 1820

printf gives unexpected result

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();
}

Upvotes: 5

Views: 595

Answers (5)

haccks
haccks

Reputation: 106102

The printf() function returns the number of characters that it prints on console.

For example after the following printf call, num_chars will have the value 10 as string "Hi haccks\n" consistes of 10 non-nul characters that will be print on screen.

num_chars = printf("Hi haccks\n");
//                  ^^^^^^^^^ ^ 
//                  12345678910    

Note: \n is single 10th char. So in above code returned value from printf assigned to num_chars variable.

In your code, in the given statement, inner printf() prints the values and then return number of chars that value printed by outer printf as shown below:

// 1              2            3
printf("%d\n", printf("%d", printf("%d",i))); // Here i = 56
         ^              ^            ^    
   print: 1       print: 2         print: 56 
   returns: 1     returns: 1       returns: 2
//    3             2               1        <--Order of printf called 

So it outputs 5621

Upvotes: 1

Arun Taylor
Arun Taylor

Reputation: 1572

It's equivalent to

#include <stdio.h>

main()
{
    int n, i = 56;
    n = printf("%d",i);
    n = printf("%d", n);
    n = printf("%d\n", n);
}

printf returns the number of characters written.

Upvotes: 6

JAB
JAB

Reputation: 21089

printf() returns the number of characters printed:

printf("%d",i) outputs the value 56.
printf("%d",printf("%d",i)) outputs 56 and then 2, the number of characters in 56.
printf("%d\n",printf("%d",printf("%d",i))) outputs 56, then 2, then the number of characters in 2, which is 1.

Upvotes: 6

orlp
orlp

Reputation: 117836

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.

Upvotes: 22

simonc
simonc

Reputation: 42205

From the printf man page

Return value

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

56 is printed for the inner printf
2 characters were printed so the argument to the next %d format specifier is 2
1 character was printed by the middle printf so the argument to the outer %d format specifier is 1
Only the outer printf includes a newline so the preceding calls output one after another on the same line, giving 5621\n.

Upvotes: 9

Related Questions