Japun Japun
Japun Japun

Reputation: 87

How to access "local" variable when a "global", "local" and "very local" variable exist having same name

int i = 1;
int main()
{
    int i = 2;
    {
        int i = 3;
        cout << ::i << endl;  //i want to print 2, neither 1 nor 3
    }
    system("pause");
    return 0;
}

I want to print 2. By default, cout << i << endl; prints 3 and cout << ::i << endl; prints 1.

Upvotes: 3

Views: 144

Answers (2)

Imobilis
Imobilis

Reputation: 1489

You may be misinterpreting the concept of scopes.

Local variables with the same name always have the priority. It just doesn't make sense otherwise, how will the compiler know which variable you are referencing to? It is considered bad practice to use variables with the same name within the same parent scope and it is evident why. Either reuse the same variable or write another function to be called.

You can create a pointer to access the outer variable and since there is an answer regarding C++ I will give an example in C

int i = 1;
int* p;
int main()
{
    int i = 2;
    p = &i;
    {
        int i = 3;
        // print *p
    }
    system("pause");
    return 0;
}

Upvotes: 1

There is no way to refer to a local name when it has been hidden by another local name in a nested scope (such as the i with value 2 by the i with the value 3). The best you can do is create a reference to it while it's still in scope:

int main()
{
    int i = 2;
    int& middle_i = i;
    {
        int i = 3;
        cout << middle_i << endl;  //will print 2
    }
    system("pause");
    return 0;
}

Of course, the actually correct solution is not to hide names you need to access, so rename one of the local i variables.


Since the question is also tagged c, be aware that C lacks both references and the scope resolution operator (::), so in C you're stuck with using a pointer (even worse than a reference in this regard), or following the "actually correct solution" even strongly and not hiding any names you intend to use.

Upvotes: 8

Related Questions