How do I explain the output of this simple C code?

后端 未结 4 2014
青春惊慌失措
青春惊慌失措 2020-12-12 06:11
#include
int main()
{
int i=10;
printf(\"%d\",printf(\"%d\",i));
return(0);
}

Output in Turbo C

102

相关标签:
4条回答
  • 2020-12-12 06:23

    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.

    0 讨论(0)
  • 2020-12-12 06:23

    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.

    0 讨论(0)
  • 2020-12-12 06:28

    Let's take apart the top level statement that produces the output:

    printf("%d",printf("%d",i));
    
    • We have a function call of printf at the top level, passing two arguments to the function
    • The first argument of the top-level printf is the format string "%d"
    • The second argument of the top-level 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.

    0 讨论(0)
  • 2020-12-12 06:30

    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).

    0 讨论(0)
提交回复
热议问题