C++ Variable Scope
π C++ Variable Scope
Variable scope defines where a variable can be accessed or used in a C++ program.
Understanding scope is essential to avoid errors and write clean, predictable code.
πΉ 1. Types of Variable Scope in C++
-
Local Scope
-
Global Scope
-
Block Scope
-
Function Parameter Scope
-
Static Scope
πΉ 2. Local Scope
A variable declared inside a function is local to that function.
β Exists only inside the function
πΉ 3. Global Scope
A variable declared outside all functions is global.
β οΈ Use carefully (can cause bugs).
πΉ 4. Block Scope
A variable declared inside {} is limited to that block.
πΉ 5. Function Parameter Scope
Function parameters act as local variables.
β‘ a and b exist only inside add().
πΉ 6. Local vs Global Variable with Same Name
β Local variable hides the global variable.
πΉ 7. Scope Resolution Operator (::)
Used to access a global variable when a local variable has the same name.
πΉ 8. Static Variable Scope
A static variable:
-
Retains its value between function calls
-
Scope is local, lifetime is global
πΉ 9. Loop Variable Scope
πΉ 10. Best Practices
-
Prefer local variables
-
Avoid unnecessary global variables
-
Use meaningful variable names
-
Limit variable scope as much as possible
β Common Mistakes
π Summary
| Scope Type | Where Accessible |
|---|---|
| Local | Inside function |
| Global | Entire program |
| Block | Inside {} |
| Parameter | Inside function |
| Static | Local scope, persistent value |
π Final Notes
-
Scope controls visibility, not lifetime
-
Lifetime and scope are different concepts
-
Proper scoping improves code safety
