为什么当我使用函数时结果会变成这样?[复制]

Why does the result come out like this when I use a function? [duplicate]

提问人:Bunzz 提问时间:9/21/2023 最后编辑:Vlad from MoscowBunzz 更新时间:9/21/2023 访问量:78

问:

#include <stdio.h>

int apple(int total, int ate);

int main(void) {
    printf("If you eat %d out of %d apples, there will be %d left.\n", 
             4, 10, apple(10, 4));
    return 0;
}

int apple(int total, int ate) {
    printf("This is a function with a passing value.\n");
    return total - ate;
}

调试此程序时,结果将如下所示。

This is a function with a passing value.
If you eat 4 out of 10 apples, there will be 6 left.

当我根据我目前所学到的知识来解释它时,结果是

If you eat 4 out of 10 apples, there will be 6 left.
This is a function with a passing value.

它应该以这种方式出现,那么为什么它以不同的方式出现呢?

我想我还不了解 C 语言的函数顺序。

C 参数 printf 函数调用

评论


答:

2赞 Vlad from Moscow 9/21/2023 #1

在此电话会议中

printf("If you eat %d out of %d apples, there will be %d left.\n", 
         4, 10, apple(10, 4));

首先,在将所有参数传递给函数之前,都会对其进行评估。

所以这个表达

apple(10, 4)

计算,函数输出其消息。之后,函数的返回值用于调用。appleappleprintf

printf 的调用无法输出此消息中的值6

If you eat 4 out of 10 apples, there will be 6 left.
                                            ^^^

在调用函数之前。apple