Redeclaration of global variable in C


Here we will see what is re-declaration of global variables in C. Does C supports this or not. Let us see the following code to get the idea about it.

Example

#include <stdio.h>
int main(){
   int a;
   int a = 50;
   printf("a is : %d\n", a);
}

Output

[Error] redeclaration of 'a' with no linkage

So we can see that we cannot re-declare local variables. Now let us see what will be the output for global variables.

Example

#include <stdio.h>
int a;
int a = 50;
int main(){
   printf("a is : %d\n", a);
}

Output

a is : 50

So global variables are not creating any error in this case. Now let us see if the first declaration is holding one value, then it can be re-declared or not?

Example

#include <stdio.h>
int a = 10;
int a = 50;
int main(){
   printf("a is : %d\n", a);
}

Output

[Error] redefinition of 'a'

So we can see that we can only re-declare global variables, when they are not initialized.

Updated on: 30-Jul-2019

528 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements