Access to a global variable hidden by local

Possible duplicate:
How to access a shadow global variable in C?

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

int m=20 ; void main() { int m=30; } 
+4
source share
4 answers

There is no way in C. in fact, introducing an extra scope and with an extern declaration, you can see @Potatoswatter's answer.

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

In addition, it is int main() .

+4
source

In C you can. Of course, these are just trifles; you should never do this in real life.

Declaring something extern can be done anywhere and always associates a declared variable with a global 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 .

+4
source

In C, you are not doing this. Give them a different name, this is confusing and bad practice anyway.

+2
source

the same name is bad practice, because until m is overridden, you somehow get access to the global variable.

  int m=20 ; void main() { print m // 20 would be printed here . // max you can do int m=30; } 
0
source

All Articles