Reputation: 793
When we declare a global variable, it is initialised to its default value. But when we initialise a variable using the extern
keyword, why does the variable retain the value with which it is initialised using the extern
keyword?
For instance, in the code below why is the output 9
and not a compile time error? Since there is no external linkage of variable x
from any other source file, so x has two copies and we are initialising the variable twice so this should be an error. Please clarify this; I am a bit confused in the flow of this code.
#include <stdio.h>
extern int x=9;
int x;
int main()
{
printf("%d",x);
return 0;
}
Upvotes: 0
Views: 48
Reputation: 141628
extern int x = 9;
means the same as int x = 9;
. The extern
keyword has no effect for a definition that already has external linkage and an initializer.
int x;
is called a tentative definition.
This is described well by C11 6.9.2/2:
A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.
This translation unit does contain an external definition for x
, so the tentative definition has no effect. It doesn't matter whether the external definition is before or after the tentative definition.
"external definition" means a non-tentative definition at file scope -- not to be confused with extern
or "external linkage", although in your example x
does happen to have external linkage.
So your code is exactly the same as:
int x = 9;
Upvotes: 1