1

I'm trying to understand the difference between compilers and interpreters.

I understand that a compiler translates a high level language directly into machine code, all in one go, seeing the entire code.

And I understand that an interpreter - rather than translating into machine code - it directly executes the commands, one at a time.

What I don't understand is how the interpreter does this? Doesn't it also end up having to produce machine code in order to do the execution?

So my question is - aren't compilers and interpreters both producing machine code, while the interpreter is just going the extra step and executing it, line by line (and then discarding the executed machine code)?

user961627
  • 12,379
  • 42
  • 136
  • 210

1 Answers1

3

A compiler parses the language and generates machine code.

An interpreter parses the language and executes the program straight away by calling specialized functions, it does not generate code.

For example, A= B + C makes a compiler generate

Load R0, $B; 
Load R1, $C;
Add R1, R0; 
Store $A, R1; 

and an interpreter directly invoke its run-time routines while parsing

....
Push("B");
....
Push("C");
....
Add();
....
Pop("A");
....

As usual, reality is more complicated as there can be pre-parsed intermediate forms as well as intermediate code that is interpreted or just-in-time compiled, but you get the idea.

I warmly recommend http://compilers.iecc.com/crenshaw/, which will show you how a parser can be embodied in either a compiler or an interpreter.

  • 1
    But how does the machine understand Push() , Add() and Pop()? There must be a binary, machine code version of these in order for the machine to be able to execute them, no? And someone has to translate the Push, Add and Pop into binary? – user961627 Feb 17 '15 at 09:30
  • 1
    Of course, but these routines are just called, they are not copied anywhere for "streamed" execution. The program is translated implicitly. –  Feb 17 '15 at 09:34
  • I see. So the main difference is that a compiler will produce the machine code for the entire program that we may then execute at will. Whereas the interpreter will produce the machine code as well, but just execute it at the same time, and we can't get a hold of it and execute it later without interpreting again? – user961627 Feb 17 '15 at 09:35
  • 1
    You shouldn't say that an interpreter "produces" machine code. It calls functions of its run-time library every now and then while parsing. No instructions are stored. Indeed a compiled program lives stand-alone and an interpreted program only executes under control of the interpreter. –  Feb 17 '15 at 09:39