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;
}
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;
}
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
.
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()
.
In C you don't. Give them a different name, it's confusing and a bad practice anyway.
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;
}