In C, when a local variable shadows a global of the same name, which value prints? #include<stdio.h> int X = 40; // global int main() { int X = 20; // local shadowing global printf("%d ", X); return 0; }

Difficulty: Easy

Correct Answer: 20

Explanation:

Introduction / Context:Identifier shadowing occurs when a local identifier has the same name as a global one. Understanding name lookup and scope rules is critical to avoiding subtle bugs.

Given Data / Assumptions:

  • A global int X = 40;
  • A local int X = 20; inside main()
  • printf("%d", X); within the function scope.

Concept / Approach:In C, the innermost scope wins. The local variable with the same name hides (shadows) the global within that block. Therefore, any unqualified reference to X inside main() refers to the local value 20.

Step-by-Step Solution:Lookup X in current scope: finds local 20.Global X is hidden within this function block.Prints 20.

Verification / Alternative check:If you removed or renamed the local X, the output would be 40. Another way to access the global (in C) is to move printing to a helper function without a local shadow.

Why Other Options Are Wrong:B: That is the global, but it is shadowed. C/D/E: No errors, and output is deterministic per C scope rules.

Common Pitfalls:Assuming the global has priority; forgetting that shadowing can confuse code readers—use distinct names to avoid ambiguity.

Final Answer:20

More Questions from Declarations and Initializations

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion