how refer to a local variable share same name of a global variable in C?

Alfred Zhong picture Alfred Zhong · Apr 29, 2011 · Viewed 15.9k times · Source

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!

Answer

David Heffernan picture David Heffernan · Apr 29, 2011

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.