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

前端 未结 4 1536
广开言路
广开言路 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:15

    The answer is No You cannot.
    A variable in local scope shadows the variable in global scope and the language provides a way for accessing the global variable by using qualified names of the global like you did. But C++ as an language does not provide anyway to access the intermediate scoped variable.

    Considering it would have to be allowed it would require a lot of complex handling, Imagine of the situation with n number of scopes(could very well be infinite) and handling of those.

    You are better off renaming your intermediate variables and using those that would be more logical and easy to maintain.

提交回复
热议问题