Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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; // local     {         int v = 3; // within subscope         cout << "subscope: " << v << endl;         // cout << "local: " << v << endl;          cout << "global: " << ::v << endl;     }     cout << "local: " << v << endl;      cout << "global: " << ::v << endl;  } 

Is there any way to access the variable v with the value 2 from the "intermediate" scope (neither global nor local)?

like image 491
Alexander Galkin Avatar asked Dec 02 '11 15:12

Alexander Galkin


2 Answers

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.

like image 80
parapura rajkumar Avatar answered Sep 30 '22 03:09

parapura rajkumar


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.

like image 37
Alok Save Avatar answered Sep 30 '22 05:09

Alok Save