Search code examples
compiler-constructioninterpreter

What is the difference between compiler and interpreter in terms of Scoping?


We say that scope of compiler is static while scope of interpreter is dynamic so what is the significance of the word Scope here and why is it static in case of compiler and dynamic in case of interpreter ?


Solution

  • We say that scope of compiler is static while scope of interpreter is dynamic

    That's not true. Whether a language is dynamically or statically scoped is a property of the language, not the implementation, and it's perfectly possible (and common) to write an interpreter for a statically scoped language (or a compiler for a dynamically scoped one for that matter, but dynamically scoped languages are just less common altogether).

    what is the significance of the word Scope here

    The scope of a variable describes in which parts of the program the variable's name refers to that variable. So if you define a variable named x on line 23 and another variable named x on line 42 and then you refer to x somewhere in your program, the scoping rules decide whether this refers to the variable defined on line 23, 42 or neither (in which case you'd usually get something like a "Variable x is not in scope" error, depending on the language).

    Dynamic scope means that a function f can see any variables that are defined in other functions that call f. This is dynamic because you can't determine (at least in the general case) which definition of f (if any) is in scope at a given place in the program without running it. So out-of-scope errors would have to be run time errors.

    Static scope (also known as lexical scope) means that a variable is in scope if and only if it's defined in a surrounding block. This is a static property that can easily be checked without running the program (unless other dynamic features get involved, such as the ability to define variables at run time), thus the term "static scope".

    why is it static in case of compiler and dynamic in case of interpreter

    It's not.