Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is scope of variable implemented in compiler at machine level or memory level

Tags:

c

scope

How is scope of a variable is implemented by compilers? I mean, when we say static variable, the scope is limited to the block or functions that defined in the same file where the static variable is defined? How is this achieved in machine level or at memory level?

How actually is this restriction achieved?

How is this scoping resolved at program run time?

like image 292
vijay kumar Avatar asked Nov 02 '12 16:11

vijay kumar


People also ask

What is the scope of a variable in programming?

In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.

How many levels of scope does a variable have?

There are mainly two types of variable scopes: Local Variables. Global Variables.

What is scope in compiler design?

The scope is determined when the code is compiled. A variable declared in this fashion is sometimes called a private variable. In a programming language, scope refers to the area where a function or variable is visible and accessible to other code.

How are variables scoped in C static or dynamic?

In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be determined by program text and is independent of the run-time function call stack.


2 Answers

It is not achieved at all at the machine level. The compiler checks for scopes before machine code is actually generated. The rules of C are implemented by the compiler, not by the machine. The compiler must check those rules, the machine does not and cannot.

A very simplistic explanation of how the compiler checks this:

Whenever a scope is introduced, the compiler gives it a name and puts it in a structure (a tree) that makes it easy to determine the position of that scope in relation to other scopes, and it is marked as being the current scope. When a variable is declared, its assigned to the current scope. When accessing a variable, it is looked for in the current scope. If not found, the tree is looked up to find the scope above the current one. This continues until we reach the topmost scope. If the variable is still not found, then we have a scope violation.

like image 136
Nikos C. Avatar answered Oct 22 '22 20:10

Nikos C.


inside compilers, its implementation defined. For example if I were writing a compiler, I would use a tree to define 'scope' and it would definitely be a symbol table inside a binary tree.

Some would use an arbitrary depth Hash table. Its all implementation defined.

like image 43
Aniket Inge Avatar answered Oct 22 '22 20:10

Aniket Inge