Accessing variables with different scope in C++

Posted by Portablejim on Stack Overflow See other posts from Stack Overflow or by Portablejim
Published on 2011-03-03T23:22:50Z Indexed on 2011/03/03 23:24 UTC
Read the original article Hit count: 162

Filed under:
|

With

#include <iostream>
using namespace std;

        int a = 1;

int main()
{
        int a = 2;

        if(true)
        {
                int a = 3;
                cout << a 
                     << " " << ::a // Can I access a = 2 here?
                     << " " << ::a << endl;
        }
        cout << a << " " << ::a << endl;
}

having the output

3 1 1
2 1

Is there a way to access the 'a' equal to 2 inside the if statement where there is the 'a' equal to 3, with the output

3 2 1
2 1

Note: I know this should not be done (and the code should not get to the point where I need to ask). This question is more "can it be done".

© Stack Overflow or respective owner

Related posts about c++

Related posts about variable-scope