Sunday, July 7, 2013

Printf in a Printf Statement

I think most of you know what an Expression means, if not click here.

So we are moving on to the complex part of the expressions, What happens when a printf() statement is included in a expression???

Before knowing about it, we go on with a simple example of expression

x=3+(y=5+6)
Do you know what would be the result of the expression, it just gives a value of 5+6 i.e., 11 to y and the value of x would be 3+y i.e., 3+11 and the value is 14.



Similarly what if an expression has printf() statement in its notation,

Consider the following program,

  1. #include<stdio.h>
  2. main()
  3. {
  4. printf("%d", 3+printf("%d", 7));
  5. return 0;
  6. }
You might be thinking that based on the previous expression solving, the value will be 10, but just check out what will be the output. The output turns out to be, 

74
Don't get confused in seeing such a value. This value is because that, while solving the printf() statement, it first executes the inner printf() statement and prints the value to the output to the screen. Hence 7 is printed. Then as the printf() has executed successfully, it returns 1 and this 1 is added to the value 3 and the next result is 4 which is printed on the screen.

Thus, a printf() statement gets executed inside a printf() and upon its successful execution it returns 1 which in an expression, replaces the entire printf() statement with a 1.