12

for example

#include<stdio.h>

int foo = 100;

int bar()
{
    int foo;
    /* local foo = global foo, how to implemented? */
    return 0;
}

int main()
{
    int result = bar();
    return 0;
}

I think in the function bar, calling foo directly will just get the global foo. How can I refer the local foo? I know in C++, there is this pointer. However, does C has something similar?

Thanks a lot!

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Alfred Zhong
  • 121
  • 1
  • 1
  • 4
  • May be you can refer to the answer by Ouah : http://stackoverflow.com/questions/12183899/how-to-print-value-of-global-variable-and-local-variable-having-same-name – Sorcrer Dec 31 '15 at 15:40

1 Answers1

16

No, by declaring foo in bar(), you have taken the global foo out of scope. Inside bar() when you refer to foo you get the local variable.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • I tried and looks like you are right. Is there any way to refer to the "global foo" inside bar() then? – Alfred Zhong Apr 29 '11 at 03:35
  • change the name of your local variable is the normal solution – David Heffernan Apr 29 '11 at 03:36
  • just doesn't look elegant, but if that is the only way, I can do that – Alfred Zhong Apr 29 '11 at 03:39
  • I don't know why the first answer is gone. I think it was a good one, tried using {extern int foo; temp = foo}, it works, Thanks to whoever come up with it then. To David: so this is not possible. However, I am still wondering if there is more elegant way. – Alfred Zhong Apr 29 '11 at 03:51
  • 4
    Conversely, in C, there is no way to refer to the global variable `foo` from inside `bar()` - at least, not once the declaration of the local variable `foo` is complete. In C++, you could use `::foo` but that is not available in C. – Jonathan Leffler Apr 29 '11 at 03:54
  • 1
    the other answerer deleted the answer because you asked how to access the local variable. C doesn't really lend itself to scope resolution and namespace like features. Just choose a different name is the elegant solution. – David Heffernan Apr 29 '11 at 03:55
  • to Jonathan: you are right, I will agree that there is no a "direct" way in C. Yes, ::foo works for C++ – Alfred Zhong Apr 29 '11 at 03:59
  • @AlfredZhong If you really have a specific variable name you want to use, i.e., it best describes the data being stored, the most elegant way I have found is to add an underscore '_' character to the beginning or end of the local variable name. For example: `static void * address; void init(void * _address) { address = _address; }` – michaelkoye Apr 22 '17 at 00:03