How can I access a shadowed global variable in C? In C++ I can use ::
for the global namespace.
Explanation: If a local variable exists with the same name as the local variable that you want to access, then the global variable is shadowed. That is, preference is given to the local variable. 6.
When inside the nested block, there's no way to directly access the shadowed variable from the outer block. However, because global variables are part of the global namespace, we can use the scope operator (::) with no prefix to tell the compiler we mean the global variable instead of the local variable.
Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
One of the first languages to introduce variable shadowing was ALGOL, which first introduced blocks to establish scopes. It was also permitted by many of the derivative programming languages including C, C++ and Java.
If your file-scope variable is not static, then you can use a declaration that uses extern in a nested scope:
int c; int main() { { int c = 0; // now, c shadows ::c. just re-declare ::c in a // nested scope: { extern int c; c = 1; } // outputs 0 printf("%d\n", c); } // outputs 1 printf("%d\n", c); return 0; }
If the variable is declared with static, i don't see a way to refer to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With