0

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.

user1071847
  • 633
  • 9
  • 20

4 Answers4

5

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

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

Jack
  • 16,276
  • 55
  • 159
  • 284
1

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.

CodeClown42
  • 11,194
  • 1
  • 32
  • 67
1

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.

Clifford
  • 88,407
  • 13
  • 85
  • 165
  • Yes, I'd like to avoid using a global variable, but I want to use the file tree walking function nftw, and I don't see a good way to pass my state information back and forth with that function. – user1071847 Apr 20 '12 at 19:29
  • Nothing about the nftw() interface suggests to me that a global variable is necessary. Perhaps you should post a question about that, with code. – Clifford Apr 21 '12 at 21:29
  • OK, I posted the question. I didn't use any code; I think the description suffices. – user1071847 Apr 23 '12 at 13:12