-4
#include <stdio.h>

int a = 33;

int main()
{
    int a = 40;
    {
        extern int a;
        printf("%d\n",a);   
    }
}

Output : 33

Can anyone please let me know how Extern is working here ?

Why after declaring variable "a" with extern keyword, access to local variable "a" in main is lost ?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
vishal
  • 41
  • 5
  • That so-called duplicate was not useful for this particular question. – Bathsheba Jun 05 '18 at 10:15
  • 1
    I also don't understand the downvoting. This is a quite a good question (especially now that muggins here has fixed a typo and formatted the question). – Bathsheba Jun 05 '18 at 10:17

2 Answers2

1

extern used in this context refers to the variable at global scope.

So your extern int a refers to the variable at global scope, and shadows the automatic a declared in main.

(The effect is similar to the ::a of C++.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

In simple terms extern int a; declares a variable named a that exists somewhere else, usually a different compilation unit. It just tells the compiler: "Trust me, that variable exists and let the linker worry about where it actually is.". It shadows the local variable ìnt a = 40;. The linker later looks for the variable and then finds the global int a = 33;.

This construct is a way to get back access to global variables that where shadowed.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42