6.2Scope and shadowing
The idea
Scope is where a name is visible: from its declaration to the end of its block. An inner variable with the same name hides the outer one.
Think of it like this: Two classmates both called Sam: in the room where one Sam is present, "Sam" means that Sam.
Why it exists
Shadowing hides a global behind a local, and static scoping means a name is resolved by where the code is written, not by who called it.
How it works
- Find the nearest enclosing declaration of the name.
- Inside an inner block it hides the outer one; the outer variable is untouched.
- When the block ends the outer name is visible again.
- A called function never sees the caller's locals; it sees its own locals and the globals.
Worked example: show() called from test()
test() has a local a = 100, but show() is written outside it, so show() prints the global a = 5.
Now play with it
- →Run inner block hides the global and watch two different x's appear.
- →Run static scoping and see 5, not 100.
Inside the braces, the new x hides the global x. After the block, the global x is visible again and unchanged.
1#include <stdio.h>2int x = 10;3int main() {4 int y = 1;5 printf("%d %d\n", x, y);6 {7 int x = 20;8 y = x + 1;9 printf("%d %d\n", x, y);10 }11 printf("%d %d\n", x, y);12 return 0;13}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
int x = 1; int main() { int x = 2; { int x = 3; } printf("%d", x); } prints
Exam notes (the dense version)
A variable is visible from its declaration to the end of its block. An inner declaration with the same name shadows the outer one, and the outer value is untouched. Globals are visible everywhere after their declaration. C uses static (lexical) scoping: a name refers to the nearest enclosing declaration in the program text, never to the caller's locals.
Previous year questions: Storage Classes, Scope & Memory (8)
PYQs are grouped by topic, so this is the full set for Storage Classes, Scope & Memory; try the ones that match this subtopic. Open all 8 on the topic page.