Question:medium

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

The Correct Option is A

Solution and Explanation

All three programs revolve around one rule: a name can be reused for a different variable if the new declaration sits in a nested inner scope, but the same name cannot be declared twice inside the same scope, no matter what type the second declaration uses.

  1. P1: declares a global variable a at file scope, then a separate local variable a inside main(). These live in two different scopes, file scope and the block scope of main, so the local a simply shadows the global one. No conflict exists, and the compiler accepts this. P1 compiles fine.
  2. P2: declares int a=5 and then int a=7, both directly inside main(), so both sit in the exact same block scope. Declaring the same name twice in one scope is not allowed in C; the compiler reports it as a redefinition error. P2 fails to compile.
  3. P3: declares int a=5 and then float a=7, again both directly inside main(). Changing the type from int to float does not fix anything, because the problem is the duplicate name in the same scope, not the type. This too is a redefinition, with a type conflict on top, so P3 fails to compile.

Since P2 and P3 both break the same-scope redeclaration rule and only P1 uses a legal nested-scope shadow, only P1 compiles without error.

Let's summarize:

  • Shadowing, the same name in a different scope such as global versus local, is legal in C.
  • Redeclaring the same name twice in the identical scope is always an error in C, whatever the type.

So the correct answer is option (A): only P1 compiles without error.

Was this answer helpful?
0

Top Questions on C Programming: Scope and Variable Shadowing


Questions Asked in GATE CS exam