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

前端 未结 4 1535
广开言路
广开言路 2020-11-28 12:31

Just out of curiosity: if I have nested scopes, like in this sample C++ code

using namespace std;

int v = 1; // global

int main (void)
{
    int v = 2; //          


        
4条回答
  •  星月不相逢
    2020-11-28 13:25

    There are two types of scope resolution operators in C++ - unary scope and a class scope. There is no function scope or "any particular parent scope" resolution operators. That makes it impossible to solve your problem, as it is, in general because you cannot refer to anonymous scopes. However, you can either create an alias, rename variables, or make this a part of the class, which of course implies a code change. This is the closest I can get you without renaming in this particular case:

    #include 
    
    using namespace std;
    
    int v = 1; // global
    
    class Program
    {
        static int v; // local
    
    public:
        static int main ()
        {
            int v = 3; // within subscope
            cout << "subscope: " << v << endl;
            cout << "local: " << Program::v << endl; 
            cout << "global: " << ::v << endl;
        }
    };
    
    int Program::v = 2;
    
    int main ()
    {
        return Program::main ();
    }
    

    There are other ways, like making sure that variables are not optimized out and are on stack, then you can work with stack directly to get the value of the variable you want, but let's not go that way.

    Hope it helps!

提交回复
热议问题