Question:

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: Jul 7, 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
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

Step 1: Analyze P1. P1 declares a global variable <code>int a=5;</code> outside <code>main()</code>, and inside <code>main()</code> it declares a local variable <code>int a=7;</code>. This is legal in C. The local declaration simply shadows the global one within <code>main()</code>'s scope; there is no conflict because they exist in different scopes. P1 compiles without error.

Step 2: Analyze P2. Inside <code>main()</code>, the same variable <code>a</code> is declared twice in the same block: <code>int a=5;</code> followed by <code>int a=7;</code>. C does not allow redeclaration of the same identifier within the same scope, so this produces a compile-time redeclaration error.

Step 3: Analyze P3. Similarly, <code>int a=5;</code> followed by <code>float a=7;</code> declares <code>a</code> twice in the same scope, this time with conflicting types. This also causes a compile-time redeclaration/conflicting-types error, regardless of the type used the second time.

Step 4: Only P1 avoids a scope conflict since its two declarations of <code>a</code> are in different scopes (global vs local), so only P1 compiles cleanly.

\[ \boxed{\text{Option (A): Only P1 will compile without any error}} \]
Was this answer helpful?
0
0

Top GATE CS Computer Science and IT Engineering Questions

View More Questions

Top GATE CS Programming in C Questions