Skip to main content

Command Palette

Search for a command to run...

scope in c++

Published
3 min readView as Markdown

🧠 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++

TypeWhere it’s definedWhere it can be used
Local ScopeInside a function or block { }Only inside that block
Global ScopeOutside all functionsAnywhere in the program
Function ScopeFunction name itselfCan be used only when called
Class ScopeInside a classAccessed 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 x hides (or shadows) the global x.

  • 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 TypeExampleAccessed By
LocalInside { }Only in that block
GlobalOutside all functionsAnywhere using ::
FunctionInside functionOnly in that function
ClassInside classUsing object or class name

More from this blog

Amit singh's blog

235 posts