I wrote following program
#include<stdio.h>
main ()
{
extern int i;
printf("\n%d",i);
}
int i=30;
I was expecting an error message as i is initialized after main but on the contrary the program gave me output.Why it did not gave me an error is what I want to know.
Because the symbol representing i is still present in the program space. By declaring it “extern”, you’re telling the compiler NOT to necessarily expect the definition of “i” before encountering it…in other words, you’re explicitly telling the compiler to trust that the symbol will be linked in later.
This, fundamentally, not any different than having a function definition in a completely separate library and declaring it extern in your main. The order is unimportant, as the symbol will still be linked in.