I was wondering why is it possible that we can use the same name for local variable in different scopes?
Like we can have two methods which both can have variable with the same name.
What makes this possible and what happens behind the scenes?
2
When the compiler enters a “new scope”, new variables within that scope are stored for that scope, and when the scope “disappears”, those variables disappears. This is, normally, done in the form of some sort of stack/list type, which in turn holds the variable names and their type.
So, if we have:
int x;
void func()
{
float x, y;
int a;
}
the stack will have level 0 with {x, int}
, and level 1 with {x, double}, {y, double}, {a, int}
.
I’ve written my own pascal compiler in C++ (using LLVM to do the actual code generation), and here’s my “name-stack”:
https://github.com/Leporacanthicus/lacsap/blob/master/stack.h
It uses the StackWrapper to keep track of the number of levels.
This should not be confused with the fact that a stack is used for nesting calls to functions, and storing the local variabls – that’s a stack in the runtime environment, and whilst both conceptually are similar, the stack in the compiler is there to track different scopes, the one in the runtime keeps track of calls to functions, arguments to functions and local variables.
3
Why can we use the same name for local variable in different scopes?
Each method has its own set of local variables. The compiler converts these local variable names, in essence, to per-method unique numbers (stack frame offsets). After compilation the names of local variables are lost (disregarding some of the newer reflection APIs).
Local variables only exist while the method is being executed and are reset each time the method is invoked.
What makes this possible and what happens behind the scenes?
Local variables are stored on the “stack”. Thus, each call to a method gets its own copy of local variables. As the methods return the space allocated on the stack is released.
This stack is also the key reason that method calls can even be recursive, where a method calls itself. Each call gets its space on the stack.
Further search for terms like “stack” and “local variable” may let you find more.
5