Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing global variable hidden by local [duplicate]

Tags:

c

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 ;  
     void main()  
     {  
       int m=30;  
     }   
like image 459
deepak Avatar asked Dec 21 '22 12:12

deepak


1 Answers

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.

like image 65
Potatoswatter Avatar answered Dec 24 '22 01:12

Potatoswatter