I am trying to understand this code:
#include<stdio.h>
int main()
{
extern int a;
printf("%d\n", a);
return 0;
}
int a=20;
When I run it, the value of a is 20. Yet this should be impossible, since the global variable a is defined at the bottom.
An
externdeclaration can only be used with variables that are global. It tells the compiler that the global variable is defined elsewhere, and asks the linker to figure it out.In your code,
extern int arefers to theadefined at the bottom of your example. It could have been equally well defined in a different translation unit.As others have pointed out, the initialization of
atakes place beforemain()is entered.