简体   繁体   中英

Explain the reason for such output of this C program

Please help me to understand the output of the following C program.

#include "stdio.h"
int fun(int x)
{
    static int a=0;
    return x+a++;
}
int main()
{
    int i;
    for(i=0;i<5;++i)
    printf("%d ",fun(printf("%d",0)));
    return 0;
}

output is : 01 02 03 04 05

why not : 1 2 3 4 5

The first 0 is the result of the execution of the printf() statement inside the fun() function call

fun(printf("%d",0))

and the second 1 is the result of the outer printf() which prints the return value of the fun() function call. The fun() function call sends the return value of the inner printf() which is always 1 , and since you have initialized the variable a as static the value of a remains same and is added everytime with the function call.

since you are always printing 0 in the printf() inside the fun() function call, hence the 0 before the numbers.

The arguments are evaluated in order when you call printf here:

printf("%d ",fun(printf("%d",0)));

The outer printf call needs to evaluate all its arguments, which is the following:

fun(printf("%d",0))

Which then calls the inner printf to evaluate all of its arguments.

First, printf("%d",0) will be evaluated, and evaluate to the number of characters printed (since this is what printf() returns). This is passed to fun next, which will return the number of characters the printf printed (1) plus the number of times it has been called (due to the static int a ). That will then be passed to the outer printf, printing the second number, then a space.

The reason is that in this statement

printf("%d ",fun(printf("%d",0)));

function printf is called twice. At first it is called as the argument expression of function fun

fun(printf("%d",0))

and outputs aways 0.

The second time the function is called with the resut of the call of function fun Take into account that the value of call

printf("%d",0)

is always equal to 1.

imagine your commands in the way that it is evaluated:

printf("%d ",fun(printf("%d",0)));

is equivalent to:

int printf_result = printf("%d",0);
int fun_result = fun(printf_result);
printf(("%d ",fun_result);

this is c. this is not python or matlab. if you assign the result value it doesn't influence the effects of the function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM