yanpas
yanpas

Reputation: 2225

How to access to variable of parent scope in c++?

Let's imagine I have piece of code like this:

#include <iostream>

int main()
{

    int a = 5;
    {
        int a = 12;
        std::cout << a;
    }

    return 0;
}

I want to cout a==5 from outside scope, but main::a doesn't work surely. Is there any workaround?

Upvotes: 5

Views: 1623

Answers (2)

Edwin Rodr&#237;guez
Edwin Rodr&#237;guez

Reputation: 1257

An alternative, it's similar to ilya answer but without polluting the parent scope

int main() {
  int a = 1;
  {
    int& outer_a = a;
    int a = 2;
    std::cout << outer_a;
  }
}

Upvotes: 1

Ilya
Ilya

Reputation: 5557

A (let's say) workaround:

int main()
{

    int a = 5;
    int *pa = &a;
    {
        int a = 12;
        std::cout << (*pa);
    }

    return 0;
}

Alternatively,

int main()
{

    int a = 5;
    int& ra = a;
    {
        int a = 12;
        std::cout << ra;
    }

    return 0;
}

Upvotes: 5

Related Questions