Scope is the region where an identifier can be used. A variable declared in a block is visible from its declaration to the closing brace (block scope); one declared outside all functions has file scope. An inner declaration can shadow an outer one.
Remember
int g = 100; /* file scope */
void f(void) {
int x = 1; /* block scope */
{ int x = 2; } /* shadows outer x */
}
Reference
Cheat Sheet
Keep these facts handy while you work with Variable Scope in C.
Topic
Detail
Block
Between { and }
File
Declared outside functions
Function
Only labels have function scope
Shadowing
Inner name hides outer name
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Lifetime and Linkage.
Example 1 — Shadowing and file-scope variables
A local counter hides the global one without changing it.
C
#include <stdio.h>
int counter = 100;
void show(void) {
printf("file-scope counter: %d\n", counter);
}
int main(void) {
int x = 1;
{
int x = 2;
printf("inner x = %d\n", x);
}
printf("outer x = %d\n", x);
show();
int counter = 5;
printf("local counter = %d\n", counter);
show();
return 0;
}
Output
inner x = 2
outer x = 1
file-scope counter: 100
local counter = 5
file-scope counter: 100
How It Works
The inner x exists only inside its braces.
Declaring a local counter hides the global in main only.
show still sees the file-scope variable.
Edge Cases & Pitfalls
Check these before relying on Variable Scope in real programs.
global
Overusing globals
Globals make code hard to test and reason about. Prefer parameters and return values.
for
Loop variable scope
A variable declared in the for header (C99) is not visible after the loop.
Remember
Key Takeaways
Block: braces start a scope.
Shadow: inner names hide outer ones.
Limit: keep scope as small as possible.
One line: Scope is the region where an identifier can be used.
Frequently Asked Questions
Local variables live in a block and exist only while it runs. Global (file-scope) variables are visible to the whole file and persist for the entire program.
Shadowing happens when an inner declaration uses the same name as an outer one, hiding the outer variable inside the inner scope.
Continue with "C Lifetime and Linkage" next. How long an object lives and which files can see its name. The C Functions hub lists every topic in order.