gpt4 book ai didi

c、指针和 printf 的参数列表。使困惑

转载 作者:行者123 更新时间:2023-12-02 08:47:09 26 4
gpt4 key购买 nike

有人可以解释为什么当我运行下面的简短代码片段时变量 test 的值没有改变吗?

#include <stdio.h>

int f1(char * foo) {
*foo = 'a';
return 0;
}

void main(void) {
char test = 'n';
printf("f1(&test)=%d. test's new value? : %c", f1(&test), test);
}

我知道我可能遗漏了一些非常简单的东西。我只是不明白为什么 f1() 中的测试没有更改,因为我正在传递它的地址,对吗?为什么实际函数调用发生在 printf() 的参数列表中很重要?

如果我像这样从 printf 参数列表中取出对 f1() 的调用:

#include <stdio.h>

int f1(char * foo) {
*foo = 'a';
return 0;
}

void main(void) {
char test='n';
int i;
i = f1(&test);
printf("f1(&test)=%d. test's new value? : %c", i, test);
}

事情按预期进行。

提前致谢。

最佳答案

函数调用参数的计算顺序是未指定的。换句话说,您无法确定何时评估 f1(&test)

因此在您的示例中,f1(&test) 可能在 test 之后被评估:有点违反直觉,您无法查看该调用的副作用。但是如果你在调用之后再次打印 test,你确实会看到它们。


最重要的是,要小心有副作用的函数,你应该被设置。

关于c、指针和 printf 的参数列表。使困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11638093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com