using nested printf statements giving strange outp

2020-04-21 07:55发布

问题:

I recently came across this code and I'm unable to understand how it works

#include<stdio.h>
int main(){
    printf("Line 1\n",
    printf("Line 2\n",
    printf("Line 3\n",
    printf("Line 4\n",
    0))));
return 0;
}

It is giving the following output:

Line 4
Line 3
Line 2
Line 1

回答1:

printf is used to print a formatted line. For example, to print an integer, you call:

printf( "%d", 1 );

What you did, is call it with the return value of the nested print as argument, which means that it first need to evaluate the nested call. Your call is similar to:

int temp;
temp = printf("Line 4\n", 0);
temp = printf("Line 3\n", temp);
temp = printf("Line 2\n", temp);
temp = printf("Line 1\n", temp);

Also, note that since you have no format specifiers in the format string, there is no meaning to the second argument, and if your compiler is nice enough it will even warn you about that.



回答2:

This isn't strange at all. Expressions are evaluated (executed) from within to outside, just like mathematical expressions.

So put it simple terms: the expression with the most parentheses around it is evaluated / executed first.

Simplified it is:

printf("1", printf("2", printf("3", printf("4"))));


回答3:

You need to evaluate the parameter of a function before actually calling it. So the most inner print is called first.



标签: c printf