在 C 中返回和操作返回值

发布于 2024-10-31 14:01:41 字数 314 浏览 5 评论 0原文

我很难理解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吝吻 2024-11-07 14:01:41

以下程序的输出是1010。我用 gcc -Wall -std=c99 main.c -o main.exe 编译它所以,我认为这要么是你的编译器问题,要么你在声称 printf("% d", one); 打印零。

#include <stdio.h>

int foo(void);

int main()
{
    int one = 0; 
    one = foo();

    printf("%d", one);
    printf("%d", foo());

    return 0;
}

int foo()
{   
     return 10; 
}

The following program's output is 1010. I compiled it with gcc -Wall -std=c99 main.c -o main.exe So, I think it's either your compiler problem, or you were wrong when claimed that printf("%d", one); prints zero.

#include <stdio.h>

int foo(void);

int main()
{
    int one = 0; 
    one = foo();

    printf("%d", one);
    printf("%d", foo());

    return 0;
}

int foo()
{   
     return 10; 
}
别想她 2024-11-07 14:01:41

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, with printf("%d", one) you are telling printf to print out a number, which does work.

情愿 2024-11-07 14:01:41

C 函数不是数学(或函数式编程)中的“函数”。

它只是获取返回值所需的一系列操作,这意味着函数可能会产生副作用。

因此,考虑一下您的示例 - 如果 foo() 看起来像这样:


int foo()
{
 printf("some text");
 return 10; 
}

换句话说,如果您使用带返回值的变量 - 您只需使用值,但如果您使用函数调用,则需要执行获取值所需的所有计算。

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:


int foo()
{
 printf("some text");
 return 10; 
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文