| 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?
A
Step-by-Step Solution
Insight: C allows variable shadowing across different scopes but forbids redeclaration within the same scope, regardless of type.
Exam route: Check the scope of each variable declaration. Global vs local is shadowing. Two locals in the same block is redeclaration.
Learning route:
- P1:
int a=5;is at file scope.int a=7;is insidemain(block scope). The localashadows the globala. This is perfectly valid C and compiles without error. - P2:
int a=5;andint a=7;are both declared inside the exact same block scope (main). This is a redeclaration error. The compiler will reject it. - P3:
int a=5;andfloat a=7;are both in the same block scope. Even though the types differ, C does not allow overloading or redeclaration with different types in the same scope. This is a compilation error. - Therefore, only P1 compiles successfully.
Trap: Believing that shadowing causes a compilation error or that different types in the same scope are allowed. Shadowing is strictly cross-scope; redeclaration is strictly intra-scope.
Verification: Compile P1 mentally: global a exists, local a hides it. No conflict. P2: compiler sees two as in main's symbol table -> error. P3: same symbol table, conflicting types -> error.