We will see how C and C behave when redeclaring a global variable without initialization, redeclaring a global variable with initialization, redeclaring a global variable and initializing it twice different. Additionally, we will repeat the above combination using local variables.
#include <stdio.h> int var; int var; int main(){ printf("Var = %d",var); return 0; }
Var = 0
#include <iostream> using namespace std; int var; int var; int main(){ cout<<"Var = "<<var; return 0; }
Compilation Error: int var; main.cpp:3:5: note: ‘int var’ previously declared here
Result: - C allows global variables to be redeclared without initialization. The value is still 0. C gives a compilation error indicating that the variable was redeclared.
#include <stdio.h> #include <stdio.h> int main(){ int var; int var; printf("Var = %d",var); return 0; }
error: redeclaration of ‘var’ with no linkage
#include <iostream> using namespace std; int main(){ int var; int var; cout<<"Var = "<<var; return 0; }
error: redeclaration of ‘int var’
Result: - Neither C nor C++ allow redeclaration of local variables without completing initialization. Both programs fail to compile.
#include <stdio.h> int main(){ int var; int var=10; printf("Var = %d",var); return 0; }
Var = 10
#include <iostream> using namespace std; int var; int var=10; int main(){ cout<<"Var = "<<var; return 0; }
main.cpp:7:9: error: redeclaration of ‘int var’ int var;
Result: -C allows redeclaration of uninitialized global variables. C program compilation failed.
#include <stdio.h> int var; int var=10; int main(){ printf("Var = %d",var); return 0; }
error: redeclaration of ‘var’ with no linkage
#include <iostream> using namespace std; int main(){ int var; int var=10; cout<<"Var = "<<var; return 0; }
error: redeclaration of ‘int var
Result: - Neither C nor C allow redeclaration of a local variable, even if it is not initialized. Both programs failed to compile
The above is the detailed content of Redeclaration of global variables in C program. For more information, please follow other related articles on the PHP Chinese website!