简体   繁体   中英

How printf work in c when one of the argument is a function call

Can anybody tell me how this program execute internally

#include<stdio.h>

typedef int (* afp)(int a, int b);

int abc(int x, int y)
{       
    return x+y;
}       

int main()
{       
    afp ab;
    ab = &abc;
    printf("\n%d - %d - %d", ab(20, 13));
    return 0;
} 

and the output obtained is

33 - 20 - 4195712

as you can see first %d is replaced with expected result 20+13 but the next %d is always replaced by the first argument to the function and the last %d is replaced by a garbage..

--EDIT

I have added three %d 's but passing only one arguments to printf, but how the second %d is always get replaced by the first argument to the function ??

You are causing undefined behavior. You specify three parameters "\\n%d - %d - %d" , yet you only pass one ab(20, 13) .

The first output is what that function call ab(20, 13) returns, the rest is not meaningful.

Since you pass one parameter you should call it like this:

printf("\n%d", ab(20, 13));
printf("\n%d - %d - %d", ab(20, 13));

What you have is undefined behavior because the number of format specifiers doesn't match the number of values which needs to be printed out.

Note: The order of evaluation within printf() is not defined if you question wanted to this information.

As other answers have already said, this is undefined behaviour, so the C standard allows a conforming C implementation to do anything.

But if you are asking what really happens in this case: When printf sees the three %d's, it will look for three arguments, in the places where they would have been, if they existed. The first one is the return value from the function call. The second one seems to be one of the arguments to that function call, that happened to be left in the place where printf looks for its second argument. And the third is some garbage. You will need to look at the details of your particular environment, and how your compiler lays out variables in memory, to know more.

What you are doing is undefined behavior.

Your printf is only getting one argument but you told it three.

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