Is there any way to access a local variable in outer scope in C++?

You can declare a new reference as an alias like so

int main (void)
{
    int v = 2; // local 
    int &vlocal = v;
    {
        int v = 3; // within subscope
        cout << "local: " << vlocal  << endl; 
    }
}

But I would avoid this practice this altogether. I have spent hours debugging such a construct because a variable was displayed in debugger as changed because of scope and I couldn’t figure out how it got changed.

Leave a Comment