Scope of Variables in C++

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:

  1. Local Scope

  2. Global Scope

  3. Function/Parameter Scope

  4. 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;
}

Output:

Counter: 1

Function Scope (Parameters)

Function parameters behave like local variables and exist only inside the function.

#include <iostream>
using namespace std;

void showSquare(int x) {  // 'x' is local to this function
    cout << "Square: " << x * x << endl;
}

int main() {
    showSquare(5);
    // cout << x; // ❌ Error: 'x' is not declared in this scope
    return 0;
}

Output:

Square: 25

Class Scope (Member Variables)

Variables declared inside a class are scoped to that class. Access depends on the access specifiers.

#include <iostream>
using namespace std;

class Person {
private:
    string name;  // Only accessible inside the class

public:
    void setName(string n) {
        name = n;
    }

    void display() {
        cout << "Name: " << name << endl;
    }
};

int main() {
    Person p;
    p.setName("Sudharsan");
    p.display();
    // cout << p.name; // ❌ Error: 'name' is private
    return 0;
}

Output:

Name: Sudharsan

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top