Question:

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

Show Hint

Reusing a name in a nested inner scope (shadowing) is fine in C; declaring the same name twice in the very same scope is always an error, whatever the type.
Updated On: Jul 22, 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: Recall C's rule about redeclaring a name in a nested (inner) scope.
C allows a variable declared in an inner block to use the same name as a variable declared in an outer scope, including a global variable. This is called shadowing: the inner declaration simply hides the outer one while the inner block is active, and the two are treated as two distinct variables with distinct storage. This is legal and produces no error.

Step 2: Evaluate P1.
P1 declares a global int a=5, and inside main() it declares a local int a=7. The local a shadows the global a; there is no conflict because they live in different scopes, file scope and block scope. P1 compiles cleanly.

Step 3: Recall C's rule about redeclaring a name in the SAME scope.
Unlike the outer-inner case, C does not allow the same identifier to be declared twice with ordinary linkage inside the very same block. The compiler treats the second declaration as an illegal redefinition of an already-defined symbol in that scope, and rejects it, whether or not the type of the second declaration matches the first.

Step 4: Evaluate P2.
P2 declares int a=5 and then, still inside the same main() block, declares int a=7 again. Both declarations are in the same scope with the same name, so this is a straight redeclaration error. P2 fails to compile.

Step 5: Evaluate P3.
P3 declares int a=5 and then, in the same main() block, declares float a=7. Even though the type changes from int to float, the identifier a is still being declared a second time in the exact same scope. The type mismatch makes it worse, not better; a conflicting-type redeclaration error is raised. P3 also fails to compile.

Step 6: Conclusion.
Only P1, where the second a sits in a nested inner scope (shadowing), compiles without error. P2 and P3 both redeclare a inside the same scope as main(), which is always an error in C.

Final Answer:
Only P1 compiles without any error. \[ \boxed{\text{Option (A)}} \]
Was this answer helpful?
0
0