Why Use the Same Name for Local Variables in Different Scopes

cjava

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?

Best Answer

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.

Related Topic