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.

4 Answers 4

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.

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

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.

0
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.

3
  • 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. Apr 20, 2012 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, 2012 at 21:29
  • OK, I posted the question. I didn't use any code; I think the description suffices. Apr 23, 2012 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.