Reputation: 2225
Let's imagine I have piece of code like this:
#include <iostream>
int main()
{
int a = 5;
{
int a = 12;
std::cout << a;
}
return 0;
}
I want to cout a==5
from outside scope, but main::a
doesn't work surely. Is there any workaround?
Upvotes: 5
Views: 1623
Reputation: 1257
An alternative, it's similar to ilya answer but without polluting the parent scope
int main() {
int a = 1;
{
int& outer_a = a;
int a = 2;
std::cout << outer_a;
}
}
Upvotes: 1
Reputation: 5557
A (let's say) workaround:
int main()
{
int a = 5;
int *pa = &a;
{
int a = 12;
std::cout << (*pa);
}
return 0;
}
Alternatively,
int main()
{
int a = 5;
int& ra = a;
{
int a = 12;
std::cout << ra;
}
return 0;
}
Upvotes: 5