0

I can't understand how are the following codes giving different outputs

#include <stdio.h>
int main()
{
        int i=43;
        printf("%d\n",printf("%d",printf("%d",i)));
        return 0;
}

output: 4321

printf("%d\n",printf("%d",printf("%d ",i)));

output: 43 31

printf("%d\n",printf("%d ",printf("%d ",i)));

output: 43 3 2

printf("%d\n",printf("%d ",printf(" %d ",i)));

output 43 4 2

printf("%d\n",printf(" %d ",printf(" %d ",i)));

output: 43 4 3

and other variations give other outputs too.

How can just a space change a number.

Thanks in advance.

mch
  • 9,424
  • 2
  • 28
  • 42
Sanjay-sopho
  • 429
  • 3
  • 15

1 Answers1

7

printf return the number of characters printed

In your case that statement can be broken like this - the output is expected:

    printf("%d\n", // 1
           printf("%d", // 2
                  printf("%d",i)    // 43
                 )
          );  // 4321

For more information, consult the standard fprintf (printf is special case of fprintf with the stream being stdout)

7.21.6.1 The fprintf function

 #include <stdio.h>
       int fprintf(FILE * restrict stream,
           const char * restrict format, ...);

The fprintf function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.

artm
  • 17,291
  • 6
  • 38
  • 54