Loading lessons...
Local Scope
Local Scope
Variables are not visible everywhere. A scope is the region where a variable can be referenced - and variables declared inside a block belong to that block only.
Inside the block
Any variable declared in a block { } (including a function body) is local to that block:
int main() {
int x = 5; // x lives in main's block
if (x > 3) {
int y = 7; // y lives only inside this if
cout << x + y; // ok: x is visible here
}
cout << y; // ERROR: y is not in scope here
return 0;
}
xis visible in the wholemainbody, including inside theif.yexists only inside theifbraces; outside, the name is gone.
Function variables are local
Parameters and variables inside a function are local: they're born when the function runs and destroyed when it returns. That's why an int x in f() and an int x in g() don't collide - they live in different scopes.
Use before declaration is illegal
A variable only exists from its declaration point onward. Referencing it earlier - or outside its block - is an error. An uninitialized local holds garbage until you give it a value.
TL;DR
- Variables declared in a block are visible only inside that block.
- A function's variables are local to that function.
- Inner blocks can use outer variables; outer blocks can't use inner ones.
- The variable is gone once its block ends.
- Use a variable only after its declaration.