Nested blocks variable scopes
Is there any way to access the rest of the ( s ) variables in the following code from the inner most block?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
using namespace std;
string s = "general scope";
namespace NS
{
string s = "NS scope";
}
int main()
{
string s = "main() scope";
{
string s = "main->Level(1) scope";
{
string s = "main->Level1->Sub-Level(1) scope";
cout << endl << s << endl;
cout << endl << ::s << endl;
cout << endl << NS::s << endl;
cout << endl << endl;
}
}
}
|
No, there's no way without declaring more stuff or renaming variables. E.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <iostream>
using namespace std;
string s = "general scope";
namespace NS
{
string s = "NS scope";
}
int main()
{
string s = "main() scope";
{
string s = "main->Level(1) scope";
auto &old_s = s;
{
string s = "main->Level1->Sub-Level(1) scope";
cout << endl << s << endl;
cout << endl << old_s << endl;
}
}
}
|
Topic archived. No new replies allowed.