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)?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With