C: can a function return a global variable?

落花浮王杯 提交于 2020-01-17 04:04:05

问题


Suppose a I have a *.c file with a global variable ("global" in the sense that it has file scope) and a function. Can the function return that variable as a value to be used in other translation units?

I assume the answer is "yes." If nothing else, I assume that in C return operates under "copy" semantics---the value of the return expression is returned. But I'm not sure.


回答1:


Yes. And you're correct: if you return something like an int, then you'll return a copy of its current. If you return a pointer, you'll give them access to the variable itself.




回答2:


Well,something like this?

a.c

int foo = 3;

int get_foo() { return foo; }

main.c

#include <stdio.h>    
#include "a.c"

int main(void)
{
    printf("%d\n", get_foo());
    return 0;
}

output:

3




回答3:


I assume the answer is "yes." If nothing else, I assume that in C return operates under "copy" semantics---the value of the return expression is returned. But I'm not sure.

You are correct.

Suppose a I have a *.c file with a global variable ("global" in the sense that it has file scope)

Keep in mind that declaring a variable globally in a .c file makes it global period. If you want it restricted to file scope, use the static modifier. You will still be able to pass the value out via a function.




回答4:


If I were pedantic I would say no. It can return the value of a global variable. That value will be an instantaneous copy, not a reference. That is to say when the global changes, the value will not change.

Beyond that for all sorts of reasons the global variable should be avoided in the first instance.



来源:https://stackoverflow.com/questions/10251390/c-can-a-function-return-a-global-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!