Redeclaration of global variable in C

Consider the below two programs:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program 1
int main()
{
   int x;
   int x = 5;
   printf("%d", x);
   return 0; 
}

chevron_right


Output in C:

redeclaration of ‘x’ with no linkage
filter_none

edit
close

play_arrow

link
brightness_4
code

// Program 2
int x;
int x = 5;
  
int main()
{
   printf("%d", x);
   return 0; 
}

chevron_right


Output in C:



5

In C, the first program fails in compilation, but second program works fine. In C++, both programs fail in compilation.


C allows a global variable to be declared again when first declaration doesn’t initialize the variable.

The below program fails in both C also as the global variable is initialized in first declaration itself.

filter_none

edit
close

play_arrow

link
brightness_4
code

int x = 5;
int x = 10;
  
int main()
{
   printf("%d", x);
   return 0;
}

chevron_right


Output:

 error: redefinition of ‘x’

This article is contributed Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up