Question:medium

Consider the following three ANSI-C programs, P1, P2, and P3.
P1
P2
P3
#include <stdio.h>
int a=5;
int main(){
int a=7;
return(0);
}
#include <stdio.h>
int main(){
int a=5;
int a=7;
return(0);
}
#include <stdio.h>
int main(){
int a=5;
float a=7;
return(0);
}
Which one of the following statements is true?

Show Hint

Check whether the two declarations of the same variable name lie in different scopes (global versus local, as in P1, which is legal) or in the exact same block (as in P2 and P3, which is illegal in C regardless of type).
Updated On: Aug 3, 2026
  • Only P1 will compile without any error
  • Only P2 will compile without any error
  • Only P3 will compile without any error
  • All three programs P1, P2, and P3 will compile without any error
Show Solution

The Correct Option is A

Solution and Explanation

The key idea behind this question is C's scope rule: a variable name can be reused only if the reuse happens in a different, nested scope, never twice within the very same block.

In P1, the outer declaration \(int\ a=5\) lives at file (global) scope, completely outside any function. The inner declaration \(int\ a=7\) lives inside \(main()\)'s block scope. Since these are two separate scopes, C treats the inner \(a\) as a new variable that simply hides the outer one while inside \(main\). No error occurs, and the program is valid.

P2 tries something different: both \(int\ a=5\) and \(int\ a=7\) appear back to back inside the same block of \(main()\). There is only one scope here, and C forbids declaring the identical name twice within one scope, so the compiler reports a redefinition error immediately at the second declaration.

P3 repeats this mistake with an added twist: after \(int\ a=5\), it declares \(float\ a=7\) in the same block. Even though the type changed from int to float, the scope conflict is identical to P2, so this too fails to compile with a conflicting-declaration error.

Since P2 and P3 both violate the same-scope redeclaration rule while P1 does not, P1 is the only program that compiles successfully.

Final answer: Option (A).
Was this answer helpful?
0


Questions Asked in GATE CS exam