4

Possible Duplicate:
How can I access a shadowed global variable in C?

How to access global variable in C , if there is local variable with same name?

int m = 20;
int main(void)
{
    int m = 30;
}
user16217248
  • 3,119
  • 19
  • 19
  • 37
deepak
  • 199
  • 2
  • 9
  • 1
    C or C++? The answer is different... Also, if you write a wrong title you can edit it... – Matteo Italia Dec 08 '12 at 10:27
  • Since the body only mentions C, I've removed the C++ tag, especially since the answers will be different: "no" and "::" (from memory, so I could be wrong). – paxdiablo Dec 08 '12 at 10:34

4 Answers4

6

In C, you can. Of course this is just trivia, you should never do so in real life.

Declaring something extern can be done anywhere, and always links the declared variable to the global of that name.

#include <stdio.h>

int i = 3;

int main( int argc, char **argv ) {
    int i = 6;

    printf( "%d\n", i );
    { // need to introduce a new scope
        extern int i; // shadowing is allowed here.

        printf( "%d\n", i );
    }
    return 0;
}

In C++, the global is always available as ::i.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
4

In C there's no way. actually, introducing an extra scope and with an extern declaration you can, see @Potatoswatter's answer.

In C++ you can look up identifiers in the global namespace using :: (as in ::m=15), which, by the way, is the same operator used to access members of "regular" namespaces (std::cout, ...).

Also, it's int main().

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
2

In C you don't. Give them a different name, it's confusing and a bad practice anyway.

PeterJ
  • 3,705
  • 28
  • 51
  • 71
0

Same name is bad practice anyway until m is redefined you are accessing the global variable anyway

int m = 20;
int main(void)
{
    printf("%d\n", m); // 20 would be printed here
    // Max you can do
    int m = 30;
}
user16217248
  • 3,119
  • 19
  • 19
  • 37