scope in c++
🧠 What is “Scope” in C++?
👉 Scope means where a variable or function can be accessed or used in your program.
Every variable in C++ lives in a certain area — called its scope.
Once you go outside that area, the variable no longer exists.
🌍 Types of Scope in C++
| Type | Where it’s defined | Where it can be used |
| Local Scope | Inside a function or block { } | Only inside that block |
| Global Scope | Outside all functions | Anywhere in the program |
| Function Scope | Function name itself | Can be used only when called |
| Class Scope | Inside a class | Accessed using object or class name |
💻 Example 1: Local vs Global Scope
#include <iostream>
using namespace std;
int x = 10; // 🌍 Global variable
int main() {
int x = 20; // 🔹 Local variable
cout << "Local x: " << x << endl; // prints 20
cout << "Global x: " << ::x << endl; // prints 10 (use :: to access global)
return 0;
}
🧾 Output:
Local x: 20
Global x: 10
✅ Here:
Local
xhides (or shadows) the globalx.To access global
x, use scope resolution operator::.
💡 Scope Resolution Operator ::
It helps you access something outside the current scope — usually global variables.
Example:
::x // refers to global x
💻 Example 2: Block Scope
#include <iostream>
using namespace std;
int main() {
int a = 5;
{
int b = 10;
cout << "Inside block: " << a << ", " << b << endl;
}
cout << "Outside block: " << a << endl;
// cout << b; ❌ Error: b not accessible here
}
🧾 Output:
Inside block: 5, 10
Outside block: 5
✅ b is local to the inner block — can’t be used outside it.
💻 Example 3: Function Scope
#include <iostream>
using namespace std;
void show() {
int x = 100;
cout << "Inside show(): " << x << endl;
}
int main() {
int x = 200;
show(); // accesses show()’s x
cout << "Inside main(): " << x << endl;
}
🧾 Output:
Inside show(): 100
Inside main(): 200
✅ Each function has its own separate scope — variables inside one function don’t affect another.
💻 Example 4: Class Scope
#include <iostream>
using namespace std;
class Student {
public:
int marks = 90;
};
int main() {
Student s;
cout << s.marks; // Accessing class variable using object
}
✅ Here, marks belongs to class scope — accessed using an object.
🧩 Summary
| Scope Type | Example | Accessed By |
| Local | Inside { } | Only in that block |
| Global | Outside all functions | Anywhere using :: |
| Function | Inside function | Only in that function |
| Class | Inside class | Using object or class name |