Tuesday, November 5, 2013

Multiple declarations of global variable is valid in C

Declaring a variable multiple times globally is perfectly valid in C. This is due to the fact that variable declaration in the local function is declaration and definition, where as global variable declaration is tentative definition. That means, global variable declaration wont allocates space , until it defined or at the end the file, it allocates to zero.

Tentative Definition: when we declare the global variable, it just declares and it wont allocate space or memory to that variable, because we may declare and define the same variable in other file using extern or similar process. So to avoid these conflicts, compiler won't allocate space until all the files compiled, then allocates and initialises to zero if not initialised. And if you try to initialise while declaring the global variable more than once you will get the compilation error.

Below is the sample C Program:


int x;
int x; //valid
int x; //valid
int x=20; //defining here so valid
//int x=30; //invalid, redefinition
int x; //valid

int main(void)
printf("%d\n", x);
int x = 40;
printf("%d\n", x);
return 0;

No comments:

Popular Posts