Nearby lessons
50 of 72C - Scope
Scope is the region of a program where a variable can be used. This lesson focuses on the two everyday scopes: local scope (a variable declared inside a function) and global scope (a variable declared outside every function).
Local Scope — Variable Inside a Function
A variable declared inside a function is local to that function. It comes into existence when the function is called and disappears when the function returns. No other function can see or use it.
Example01
Global Scope — Variable Outside Functions
A variable declared outside every function is global. It is visible to all functions below its declaration, and every function shares the same copy.
Example02
Local vs Global
| Local variable | Global variable | |
|---|---|---|
| Declared | Inside a function | Outside all functions |
| Usable in | Only that function | Every function |
| Lifetime | Until the function returns | Whole program |
| Default value | Uninitialised (garbage) | Zero |
Example03
📝 Key Takeaways
- A local variable is declared inside a function and is usable only there.
- A global variable is declared outside every function and is usable everywhere.
- Local variables are created on entry and destroyed when the function returns.
- Globals live for the whole program and are shared by all functions.
- Prefer local variables; use globals only when truly needed.
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3