在 C 中返回和操作返回值
我很难理解 C 处理返回值的方式。举例来说,我们有:
int one = 0;
one = foo(); // Why isn't one being assigned 10?
// Clearly there is a difference between these two
printf("%d", one); // one is still 0
printf("%d", foo());
int foo()
{
return 10;
}
我似乎无法阐明为什么存在差异,以及为什么一个不能优于另一个。
谢谢你!
I'm having a hard time understanding the ways C handles returned values. Say for example we have:
int one = 0;
one = foo(); // Why isn't one being assigned 10?
// Clearly there is a difference between these two
printf("%d", one); // one is still 0
printf("%d", foo());
int foo()
{
return 10;
}
I can't seem to elucidate why there is a difference, and why one won't work over the other.
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下程序的输出是
1010
。我用 gcc -Wall -std=c99 main.c -o main.exe 编译它所以,我认为这要么是你的编译器问题,要么你在声称printf("% d", one);
打印零。The following program's output is
1010
. I compiled it withgcc -Wall -std=c99 main.c -o main.exe
So, I think it's either your compiler problem, or you were wrong when claimed thatprintf("%d", one);
prints zero.printf() 的第一个参数是 const char *(指向 const char 数组的指针),并且使用
printf(foo())
您尝试使用指向地址 10 的指针,这显然超出了程序的范围,导致它无法工作。但是,使用 printf("%d", one) 可以告诉 printf 打印出一个数字,这确实有效。The first argument of printf() is a const char *, (a pointer to an array of const char's), and with
printf(foo())
you're trying to use a pointer to address 10, which obviously is out of the range of the program, causing it to not work. However, withprintf("%d", one)
you are telling printf to print out a number, which does work.C 函数不是数学(或函数式编程)中的“函数”。
它只是获取返回值所需的一系列操作,这意味着函数可能会产生副作用。
因此,考虑一下您的示例 - 如果 foo() 看起来像这样:
换句话说,如果您使用带返回值的变量 - 您只需使用值,但如果您使用函数调用,则需要执行获取值所需的所有计算。
C function is not "function" as in math (or as in functional programming).
It just sequence of actions needed to obtain return value, and this mean that function may obtain side effects.
So think about your example - what if foo() will look like this:
In other words, if you use variable with returned value - you just use value, but if you use function call, you do all computations needed for obtaining value.