Reputation: 117
#include<stdio.h>
int main()
{
int i=10;
printf("%d",printf("%d",i));
return(0);
}
Output in Turbo C
102
I am a beginner. So can you explain how this code works?
Upvotes: 0
Views: 192
Reputation: 134336
Quoting C11
, chapter §7.21.6.1
The
fprintf
function returns the number of characters transmitted, or a negative value if an output or encoding error occurred.
In your case, the inner printf()
call is the argument to the outer printf()
, so the inner function call will be executed, as per the rule of function parameter evaluation.
So, in your case, first the inner printf()
executes, printing the value of i
, i.e., 10
(2 characters) and the return value of the printf()
call is used as the argument to the %d
format specifier in outer printf()
, printing 2
.
As there is no visual separator present, you see the outputs adjacent to each other, appearing as 102
.
Upvotes: 0
Reputation: 726639
Let's take apart the top level statement that produces the output:
printf("%d",printf("%d",i));
printf
at the top level, passing two arguments to the functionprintf
is the format string "%d"
printf
is the result of invoking printf("%d",i)
The argument of top-level printf
, i.e. printf("%d",i)
, needs to be evaluated prior to making the call. The expression has a value, and a side effect. The side effect is printing "10"
to the output, and the value is the number of characters printed, i.e. 2
.
Since the arguments are evaluated prior to making a call, the printf("%d",i)
is invoked first, producing the output 10
. Now the top-level printf
is invoked, and it produces the output 2
, completing the "102"
sequence that you see.
Upvotes: 1
Reputation: 4002
printf() is a C function. It returns an int value equal to the number of bytes it prints.
In your case, the INNER printf printed "10", so it wrote 2 bytes and will return 2.
The OUTER printf will therefore print "2".
Final result: "102" ("10" of the INNER followed by "2" of the OUTER).
Upvotes: 0
Reputation: 21542
The documentation for printf
states that it will return an integer that represents the number of characters written to the output stream.
That means you can use the return value of printf
to satisfy a %d
format specifier in another call to printf
, and the second (outer) call will print out the number of characters written in the first call.
i
is equal to 10
, so the first call to printf
outputs the number 10
and returns 2
(number of characters in the string "10"
), which is passed to the second call to printf
, which prints 2
, giving you the final output 102
.
Upvotes: 2