Why is initialization required for variables that are declared
globally with the extern keyword?
When we use extern keyword with uninitialized variable compiler think variable has initialized somewhere else in the program. For example:
#include <stdio.h>
extern int i; //extern variable
int main()
{
printf("%d",i);
return 0;
}
Output:
undefined reference to `i'
because, memory is not allocated for these variable. Hence in second case compiler is showing error unknown symbol i. That's why allocate the memory for extern variables it is necessary to initialize the variables. Like,
extern int i;
int i = 10;
Why is initialization not required for variables that declared
globally without the extern keyword?
When we don't use extern keyword then compiler initialized it with default value. For example:
#include <stdio.h>
int i; //By default it is extern variable
int main()
{
printf("%d",i);
return 0;
}
Output:
0
because, Compiler will automatically initialize with default value to extern variable.