using nested printf statements giving strange output

后端 未结 3 1128
长情又很酷
长情又很酷 2021-01-23 17:55

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

#include
int main(){
    printf(\"Line 1\\n\",
    printf(\"Line 2\\n\         


        
相关标签:
3条回答
  • 2021-01-23 18:29

    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"))));
    
    0 讨论(0)
  • 2021-01-23 18:33

    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.

    0 讨论(0)
  • 2021-01-23 18:36

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

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