Loading lessons...
Scope
Scope
Every name in C++ has a scope: the region of the program where it can be seen and used. Where a variable is declared decides where you can reach it.
Local scope
A variable declared inside a function or block is local. It only exists from its declaration to the end of that block:
int main() {
int x = 5; // x is local to main
cout << x; // fine, x is in scope
return 0;
}
// x no longer exists out here
A local variable cannot be used outside its block - the compiler will complain that the name is unknown.
Global scope
A variable declared outside all functions (at the top of the file) is global. It can be seen and used by every function in the file:
int x = 5; // global: visible everywhere below
int main() {
cout << x; // fine, global x is in scope
return 0;
}
Block scoping with braces
Any pair of curly braces { } creates a new scope, even a standalone block. A variable declared inside a block is limited to that block:
int main() {
{
int y = 3; // y lives only inside this block
cout << y; // fine
}
cout << y; // ERROR: y is out of scope here
return 0;
}
The name visibility rules
- A local variable shadows (hides) a global with the same name inside that block.
- A variable is usable only after its declaration point, within its scope.
- Inner scopes can see outer scopes, but outer scopes cannot see inner ones.
int x = 10; // global x
int main() {
int x = 20; // local x shadows the global
cout << x; // prints 20
return 0;
}
TL;DR
- Local scope: declared inside a function/block, visible only there.
- Global scope: declared outside all functions, visible everywhere below.
- Braces
{ }create a scope; a block's variables end with its closing brace. - Inner scopes see outer names; outer scopes never see inner ones.
- A local with the same name hides the global in that block.