开发者

Returning and manipulating returned values in C

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 assigne开发者_运维知识库d 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!


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; 
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜