In C++, the scope of a variable refers to the region of the code where that variable is accessible and valid. Understanding variable scope is essential for writing clean, efficient, and bug-free code. Let’s break it down clearly and deeply with examples.
Types of Variable Scope in C++
C++ primarily defines four types of variable scope:
-
Local Scope
-
Global Scope
-
Function/Parameter Scope
-
Class/Object Scope (Member Variables)
Local Scope
A variable declared inside a block (curly braces {}) is local to that block and cannot be accessed outside.
#include <iostream>
using namespace std;
void greet() {
int age = 20; // Local variable
cout << "Age inside function: " << age << endl;
}
int main() {
greet();
// cout << age; // ❌ Error: 'age' is not declared in this scope
return 0;
}
Output:
Age inside function: 20
Global Scope
A variable declared outside all functions is accessible anywhere in the program after its declaration.
#include <iostream>
using namespace std;
int counter = 0; // Global variable
void increment() {
counter++;
}
int main() {
increment();
cout << "Counter: " << counter << endl;
return 0;
}