How to access a global variable if there is a local variable with same name in C++?

In this article, we are going to see how to access a global variable if there is already a local variable with the same name in C++?
Submitted by Radib Kar, on August 28, 2020

In the below example,

We see there is a local variable which has same name as a global variable. If we execute the below program, then the output will be:

#include <iostream>
using namespace std;

//global variable
int var = 10;

int main()
{
    //local variables
    //outer scope
    int var = 5;
    {
        //inner scope
        int var = 1;
        cout << "var(inner scope): " << var << endl;
    }
    cout << "var(outer scope): " << var << endl;

    return 0;
}

Output:

var(inner scope): 1
var(outer scope): 5

In the above example, we see the global variable is also declared as locally and that's why it took the value of local scope. To ensure, it takes the global scope value, we need to use scope resolution operator to populate the global scope value.

Below is the modified version:

#include <iostream>
using namespace std;

//global variable
int var = 10;

int main()
{
    //local variables
    //outer scope
    int var = 5;
    {
        //inner scope
        int var = 1;
        cout << "var(inner scope): " << var << endl;
        //using scope resolution operator access the global value
        cout << "var(global value in inner scope): " << ::var << endl;
    }
    cout << "var(outer scope): " << var << endl;
    //using scope resolution operator access the global value
    cout << "var(global value in outer scope): " << ::var << endl;

    return 0;
}

Output:

var(inner scope): 1
var(global value in inner scope): 10
var(outer scope): 5
var(global value in outer scope): 10


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.