Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a shadowed global variable in C?

How can I access a shadowed global variable in C? In C++ I can use :: for the global namespace.

like image 893
vitaly.v.ch Avatar asked Mar 06 '09 12:03

vitaly.v.ch


People also ask

When a global variable is shadowed in a program if a?

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.

How can a global variable be shadowed?

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.

How can you access a global variable inside the function in C?

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.

Does C allow variable shadowing?

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.


1 Answers

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.

like image 89
Johannes Schaub - litb Avatar answered Sep 19 '22 13:09

Johannes Schaub - litb