简体   繁体   English

当其中一个参数是函数调用时,printf如何在c中工作

[英]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 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.. 正如你所看到的,首先%d被替换为预期结果20 + 13但是下一个%d总是被函数的第一个参数替换,最后一个%d被垃圾代替。

--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 ?? 我添加了3%d但是只向printf传递了一个参数,但是第二个%d总是被函数的第一个参数替换掉?

You are causing undefined behavior. 您正在导致未定义的行为。 You specify three parameters "\\n%d - %d - %d" , yet you only pass one ab(20, 13) . 您指定了三个参数"\\n%d - %d - %d" ,但您只传递了一个ab(20, 13)

The first output is what that function call ab(20, 13) returns, the rest is not meaningful. 第一个输出是函数调用ab(20, 13)返回的内容,其余的没有意义。

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. 注意:如果您对此信息有疑问,则不会定义printf()的评估顺序。

As other answers have already said, this is undefined behaviour, so the C standard allows a conforming C implementation to do anything. 正如其他答案已经说过的那样,这是未定义的行为,因此C标准允许符合C的实现做任何事情。

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. 但是如果你在问这个案例中究竟发生了什么:当printf看到三个%s时,它会查找三个参数,如果它们存在的话就会出现它们的位置。 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. 第二个似乎是该函数调用的参数之一,恰好留在printf查找其第二个参数的位置。 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. 你的printf只得到一个参数,但你告诉它三个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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