Loading lessons...
Scope
Scope
Scope decides where a variable can be seen. Variables are born, live, and die in scoped regions.
Local variables
Variables declared inside a function are local: only that function can see them.
void myFunction() {
int x = 10; // local to myFunction
}
Outside myFunction, x doesn't exist.
Block scope
Variables inside { } blocks (like an if) are only alive inside that block.
if (1) {
int y = 5; // only visible inside the braces
}
printf("%d", y); // error: y is gone
Global variables
Variables declared outside any function are global: every function can read and write them.
int shared = 0; // global
void up() { shared++; }
Use globals sparingly
Globals are convenient but make code harder to track. Prefer passing values via parameters.
TL;DR
- Scope = where a name is visible.
- Local variables live inside their function.
- Block-scoped variables die at their closing brace.
- Globals are visible everywhere; use them sparingly.