Nearby lessons
81 of 124C - Scope
Scope is the region of a program where a name is visible. Learn C's four scopes — block, function, file and global — plus variable shadowing, lifetime, and why local variables should be your default.
Block Scope
A variable declared inside braces exists only inside those braces — including the body of an if or a for:
Loop Variables Are Block-Scoped
Declaring the counter in the for header keeps it out of the surrounding code — good practice in C99 and later:
Function Scope
Each function has its own private set of names. Two functions may both use count with no interference:
Global Scope
A variable declared outside every function is visible to all of them — and modifiable by all of them:
Shadowing — Inner Wins
When an inner declaration reuses an outer name, the inner one hides the outer one for the rest of that block:
Scope vs Lifetime
static local has narrow scope but a long lifetime: only its function can name it, yet its value survives between calls.File Scope with static
static on a global restricts it to its own .c file — a module-private variable:
The Four Scopes
| Scope | Declared | Visible | Lifetime |
|---|---|---|---|
| Block | Inside braces | To the closing brace | Until the block exits |
| Function | In the body | Throughout the function | Until the function returns |
File (static) | Outside functions, with static | That .c file only | The whole program |
| Global | Outside functions | All files (with extern) | The whole program |
Parameters Have Function Scope
Parameters behave like locals declared at the top of the body — visible throughout the function, invisible outside it:
Why Globals Cause Trouble
Any function can change a global, so tracking down a wrong value means reading the whole program:
The Same Logic Without Globals
Pass the value in, return the result out. Now every function's behaviour is visible at the call site:
Common Mistakes
- Using a variable outside its block — the "undeclared identifier" error.
- Accidental shadowing — an inner variable silently hides the one you meant to update.
- Expecting a local to persist — it resets every call unless declared
static. - Reaching for a global to avoid a parameter — convenient now, painful later.
- Declaring the loop counter outside the loop — leaks the name into the surrounding scope.
- Assuming an uninitialised local is zero — only globals and statics are zero-initialised.
int total; while a global total also exists, every assignment inside that function updates the local and the global never moves. Build with -Wshadow to be warned.- A variable is visible from its declaration to the end of its enclosing block.
- Local variables are destroyed when their block exits.
- An inner declaration shadows an outer one of the same name.
- Globals are visible everywhere and are best avoided.
- static gives a local variable a lifetime that spans all calls.