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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.