r/AskComputerScience • • Apr 25 '21

Does all programming turn into machine code?

I don’t know if this question makes sense but when you write code in whatever language, python, C, Java etc does it all eventually get converted into assembly and then machine code?

35 Upvotes

32 comments sorted by

View all comments

22

u/[deleted] Apr 25 '21

I don't think assembly is a requirement but yes every language gets turned into machine code. It's just a matter of WHEN. Compiled languages and turned into machine code before you run the code. So a compiled language turned into an exacutable file is fully compiled. Meanwhile, interpreted languages are always compiled as you run the code. So a interpreted exacutable would likely be a bunch of text files that get compiled while you're using the program. Wither way, every language needs to convert the code to machine code.

26

u/teraflop Apr 25 '21

Meanwhile, interpreted languages are always compiled as you run the code.

This is not really accurate.

In an interpreted language, the code is translated into some kind of data structure that represents the instructions (which might be as simple as a list of strings, or something more complex like an abstract syntax tree).

In order to execute the code, an interpreter has to look at the data structure and follow the instructions. But the instructions are never translated into machine code. The only machine code that's running is the interpreter's code. So, for instance, if you want to take an interpreter and port it to a new CPU architecture, you might need to recompile the interpreter itself, but you don't need to modify the interpreter's code to take into account a different kind of machine code.

As an analogy, think about typing text into a word processing program. There's going to be some kind of data structure that keeps track of where each typed letter appears on the page. And you can think of this data structure as being "instructions" for rendering a page (either on a screen or a printer). But the text is never represented in the form of machine code; it's just data that the word processor's code is operating on.

If a system translates source code into machine code "on the fly", it would be more correct to call it a just-in-time compiler, not an interpreter.

5

u/ggchappell Apr 25 '21

Yes, basically. But I would add just one more little tweak.

What is an interpreter? It is a program that takes source code and executes it. Any such program is an interpreter, regardless of how it happens to accomplish its task.

it would be more correct to call it a just-in-time compiler, not an interpreter.

And an interpreter might involve a JIT compiler. That's an implementation detail -- albeit an often important one. It doesn't stop the program from being an interpreter.