C Program to Redeclaration of global variable

CServer Side ProgrammingProgramming

We will understand how C and C++ behave differently in case we re-declare a global variable without initializing, redeclaring global variables with initialization, redeclaring global variables and initializing them twice. Also, we will repeat above combinations with local variables.

1. A) C program : Redeclaring Global variables with no initialization

#include <stdio.h>
int var;
int var;
int main(){
   printf("Var = %d",var);
   return 0;
}

Output

Var = 0

B) C++ program : Redeclaring Global variables with no initialization

#include <iostream>
using namespace std;
int var;
int var;
int main(){
   cout<<"Var = "<<var;
   return 0;
}

Output

Compilation Error: int var;
main.cpp:3:5: note: ‘int var’ previously declared here

Results:- C allows redeclaration of global variables without initialization. Value remains 0. C++ gives a Compilation error that the variable is redeclared.

2. A) C program : Redeclaring Local variables with no initializations

#include <stdio.h>
#include <stdio.h>
int main(){
   int var;
   int var;
   printf("Var = %d",var);
   return 0;
}

Output

error: redeclaration of ‘var’ with no linkage

B) C++ program : Redeclaring Local variables with no initialization

#include <iostream>
using namespace std;
int main(){
   int var;
   int var;
   cout<<"Var = "<<var;
   return 0;
}

Output

error: redeclaration of ‘int var’

Results:- Both C and C++ do not allow redeclaration of local variables with no initialization done. Both programs failed in compilation.

3. A) C program : Redeclaring Global variables with initialization

#include <stdio.h>
int main(){
   int var;
   int var=10;
   printf("Var = %d",var);
   return 0;
}

Output

Var = 10

B) C++ program : Redeclaring Global variables with initialization

#include <iostream>
using namespace std;
int var;
int var=10;
int main(){
   cout<<"Var = "<<var;
   return 0;
}

Output

main.cpp:7:9: error: redeclaration of ‘int var’
int var;

Results:-C allows redeclaration of Global variable if it is uninitialized. C++ program fails during compilation.

4. A) C program : Redeclaring Global variables with initialization

#include <stdio.h>
int var;
int var=10;
int main(){
   printf("Var = %d",var);
   return 0;
}

Output

error: redeclaration of ‘var’ with no linkage

B) C++ program : Redeclaring Local variables with initialization

#include <iostream>
using namespace std;
int main(){
   int var;
   int var=10;
   cout<<"Var = "<<var;
   return 0;
}

Output

error: redeclaration of ‘int var

Results:-Both C and C++ do not allow redeclaration of local variables even if it is uninitialized. Both programs failed in compilation

raja
Published on 03-Nov-2021 05:22:57
Advertisements