Reputation:
I was wondering about why an entity can be re-utilized in an inner scope? Like if i declared the variable x within a scope, then I am able to create another variable with the exact same in an inner scope. Does the computer remove the memory for the outer entity and then replace it with the inner entity then? Or what happens? Why even have this opportunity to do so? What is it good for? It only confuses me
Thanks! I hope that it is explained good enough
Update: By "entity", I guess I mean identifier. An example of what confuses me:
int main()
{
int x = 22;
int y = 33;
{
int x;
x = 44; //now it is another variable
y = 55; //now y (outer scope) is changed
}
}
Upvotes: 0
Views: 33
Reputation: 62110
The computer as a whole is not terribly concerned with your variables and your scopes. You probably mean to say "the compiler".
No, the compiler does not "remove the memory for the outer entity and replace it with the inner entity". The compiler allocates an area of memory for your x
in the outer scope, and another area of memory for your x
in the inner scope, and simply knows that when you are in the outer scope, x
refers to the first area of memory, while when you are in the inner scope, x
refers to the second area of memory. So, it is all quite efficient.
When this happens, we say that the inner x
"shadows" the outer x
. (Sometimes you might also hear it being referred to as "masks".)
Of course when your inner scope terminates, x
refers to the first area of memory again, so nothing has been removed.
Opinions differ as to whether this is useful and beneficial, or whether it should be avoided. I believe it is useful and beneficial, because what you are doing with shadowing is that you are saying that "the name x
now stands for a different entity than the entity that it stands for in the outer scope", and you are thus prevented from accidentally accessing the entity of the outer scope from within the inner scope. The fewer variables your code has to choose from, the better.
Upvotes: 1