33
Total Posts
3
Categories
24/7
Updated

C++

Write a C++ program to use scope resolution operator. Display the various values of the same variables declared at different scope levels.

Published on Dec 22, 2025
#include <iostream>
using namespace std;

// Global variable
int x = 100;

class Demo {
public:
    int x;   // Class member variable

    void show() {
        int x = 10;  // Local variable

        cout << "Local x       = " << x << endl;
        cout << "Class x       = " << this->x << endl;
        cout << "Global x      = " << ::x << endl;
    }
};

int main() {
    Demo obj;
    obj.x = 50;

    obj.show();

    return 0;
}

Documentation

Output

Local x       = 10
Class x       = 50
Global x      = 100

 

  • x inside show()local variable

  • this->xclass data member

  • ::xglobal variable

  • Scope resolution operator helps differentiate variables with same name in different scopes.