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?
The var keyword is limited to function scope, meaning that new scope can only be created inside functions. Function and block scopes can be nested. In such a situation, with multiple nested scopes, a variable is accessible within its own scope or from inner scope. But outside of its scope, the variable is inaccessible.
Nothing physical happens. A typical implementation will allocate enough space in the program stack to store all variables at the deepest level of block nesting in the current function. This space is typically allocated in the stack in one shot at the function startup and released back at the function exit.
The Script scope is a useful place to store variables which must be shared without exposing the variable to the Global scope (and therefore to anyone with access to the session). For example, the following short script stores a version number in a script-level variable.
One of the basic reasons for scoping is to keep variables distinct from each other in multiple parts of the program. For example the programmers can use same variables for all loops such i and j, this can lead collision of variables hence the scope of the variable is necessary to avoid collisions and for more security.
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;
}
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;
}
}
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