Suppose this is the call stack of my program at a particular point:
| b = 2 |
| c = 3 | <- function f2
| return address |
| function args |
| ... |
| c = 10 | <- function f1
| ... |
f1() calls f2().
When variable c is referenced, how is it resolved? Is the stack searched linearly top down to find the first variable named c in scope, or is there some other mechanism that takes care of this more efficiently?
If the stack is searched every time, wont it be an overhead when a non existent variable d is referenced, because the stack will be searched all the way to find out that there is no such variable in scope?
In C++, during runtime the variables don’t have names. Variable names are only there for the convenience of the programmer. Variables have scope in the code, they don’t have a scope in the stack.
So the stack is not searched during runtime. During compilation the variable name is converted into a memory address.