I'm recently studying C++ language.

I have been wondered how to access local variable "a" of local area[1] at local area[2] watching the follow code.

How to do that?

#include "stdafx.h"
using namespace std;

///// global area /////
int a = 1;

int _tmain(int argc, _TCHAR* argv[])
{
    ///// local area[1] /////
    int a = 2; //<= how to access this "a" at local area[2]?

    cout << "global area [a] : " << ::a << endl;
    cout << "local area[1] [a] : " << a << endl;
    {
        ///// local area[2] /////
        int a = 3;
        cout << "global area [a] : " << ::a << endl;
        cout << "local area[2] [a] : " << a << endl;
        cout << "local area[1] [a] : " << ?????? << endl;
    }

    return 0;
}
有帮助吗?

解决方案

You can't do this. When you declare a variable in the inner scope, it shadows the outer scope's variable and the language doesn't provide any way to access it like it does for global variables.

Even if it did support this however, it would still be bad practice to name your variables the same. Imagine having to handle a large number of scopes and the complexity that would be required!

Simply use different variable names for intermediate variables, it makes both writing and maintaining the code easier.

其他提示

You need a bit of help from the outer scope:

using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
    ///// local area[1] /////
    int a = 2; //<= how to access this "a" at local area[2]?
    int& alternative_name = a;

    cout << "global area [a] : " << ::a << endl;
    cout << "local area[1] [a] : " << a << endl;
    {
        ///// local area[2] /////
        int a = 3;
        cout << "global area [a] : " << ::a << endl;
        cout << "local area[2] [a] : " << a << endl;
        cout << "local area[1] [a] : " << alternative_name << endl;
    }

    return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top