I. What Is a Programming Language?
Every day we use computers to accomplish all kinds of tasks: opening web pages, editing documents, playing videos, processing data, running AI models. Behind each of these operations, a program is directing the computer to perform a specific task.
A program is not text that a computer understands by nature; it is a series of instructions written by humans according to specific rules.
A programming language is a formal language used to describe computational processes, express the logic of operations, and enable a computer to carry out those operations.
For example, here is a short Python program:
name = "Alice"
print("Hello, " + name)
It expresses two operations:
- Create a variable
nameand store the string"Alice"in it. - Output the greeting to the screen.
Programmers can read this code directly and understand what task it is meant to accomplish.
But a computer's processor cannot directly understand words like name, print, or Hello. They must go through a series of transformations before becoming machine instructions the processor can execute.
1. What Problems Do Programming Languages Solve?
Computer hardware is essentially built from electronic circuits, and the operations a processor can perform are very basic, for example:
- Read data from memory.
- Add two numbers.
- Compare two numbers.
- Jump to other instructions based on a condition.
- Write the result back to memory.
If programmers had to build complex applications directly from these low-level operations, development would be extremely difficult.
For example, to implement a simple user login feature, a program needs to:
- Get user input.
- Read the account and password.
- Query the database.
- Compare the authentication information.
- Determine the authentication result.
- Return the login status.
If all of this had to be expressed in processor instructions, programmers would have to pay attention to a great many low-level details.
Programming languages use abstraction to organize complex hardware operations into syntax and structures that are easier to understand.
username = input("请输入用户名:")
password = input("请输入密码:")
if username == "admin" and password == "123456":
print("登录成功")
else:
print("登录失败")
This code describes business logic using language constructs such as variables, conditional statements, input, and output, without requiring the programmer to control the circuits inside the processor directly.
2. The Core Roles of Programming Languages
| Role | Description |
|---|---|
| Express logic | Describe computational tasks, conditional branching, and execution order |
| Abstract away hardware | Hide low-level details such as registers, memory, and instructions |
| Organize programs | Organize code using functions, modules, classes, and packages |
| Manage data | Provide data structures such as integers, strings, arrays, and objects |
| Control execution | Describe loops, branches, exceptions, and concurrency |
| Facilitate collaboration | Let developers understand programs through a shared syntax and set of rules |
You can think of a programming language as a standardized system of expression: programmers describe the task, and language tools convert that description into a form the computer can execute.
II. Why Can't Machines Understand Code Directly?
Answering this question requires first understanding what computer hardware can actually recognize.
1. Computers Ultimately Process Binary Data
Modern computers perform computation and control mainly through digital circuits.
In digital circuits, electrical signals are typically divided into distinct logic states, most commonly:
- Logic 0: represents one voltage range.
- Logic 1: represents another voltage range.
These logic states form the basis of binary representation.
The data in a computer — numbers, text, images, audio, and program instructions — must all ultimately be encoded in binary form before the hardware can store and process it.
For example:
| Decimal | Binary |
|---|---|
| 0 | 00000000 |
| 1 | 00000001 |
| 2 | 00000010 |
| 5 | 00000101 |
| 10 | 00001010 |
| 65 | 01000001 |
But note:
Binary data is not necessarily machine instructions.
The same set of binary bits can be interpreted, depending on context, as:
- An integer.
- A character encoding.
- A memory address.
- A floating-point number.
- A machine instruction.
- Image pixel data.
Only by knowing the data type, instruction encoding, and execution context can a computer determine what these binary bits represent.
2. A CPU Can Only Execute the Machine Instructions Defined by Its Instruction Set
A CPU is not a general-purpose interpreter that can understand arbitrary binary content.
Every processor architecture has its own instruction set architecture, or ISA (Instruction Set Architecture).
The ISA defines which machine instructions a processor can recognize and execute, and how these instructions are encoded.
For example, common instruction set architectures include:
| Instruction Set Architecture | Common Applications |
|---|---|
| x86-64 | Desktop computers, servers |
| ARM64 / AArch64 | Phones, tablets, servers, embedded devices |
| RISC-V | Education, embedded devices, processor development |
| WebAssembly | Browsers and other runtime environments that support Wasm |
Different instruction set architectures may have different machine instruction encodings and execution rules.
For example, the following is a conceptual assembly example:
mov eax, 5
add eax, 3
It means:
- Place the value 5 into register EAX.
- Add the value 3 to EAX.
The processor executes encoded machine instructions; it does not directly read and understand assembly mnemonics such as mov and add.
3. There is a difference in levels of expression between human language and machine instructions
Humans are accustomed to using words with semantic meaning to express complex intentions.
For example:
total = price * quantity
When humans see this code, they can understand that it represents the unit price of a product multiplied by the quantity.
But the processor does not know what business concepts price, quantity, and total represent.
To the processor, these identifiers need to be converted into specific storage locations, register operations, and arithmetic instructions.
Therefore, there is an obvious difference in abstraction levels between programming languages and machine instructions.
| Level | Example | Primary Audience |
|---|---|---|
| Natural language | Calculate the total price of goods | Human communication |
| High-level language | total = price * quantity |
Programmers |
| Assembly language | Mnemonics such as imul and mov |
Low-level program development |
| Machine language | Binary instruction encoding | Processor |
| Digital circuits | Logic gates, voltage states | Hardware circuits |
This does not mean that high-level languages are necessarily better than low-level languages; rather, languages at different levels serve different development goals.
III. What Happens Between Code and Machine Execution?
Source code written by programmers usually needs to be processed by a compiler, interpreter, or other runtime system before it can actually be executed.
A typical compiled program can be abstracted as:
flowchart TD
A["Source Code"] --> B["Lexical Analysis"]
B --> C["Syntax Analysis"]
C --> D["Semantic Analysis"]
D --> E["Intermediate Representation IR"]
E --> F["Code Optimization"]
F --> G["Target Code Generation"]
G --> H["Assembly and Linking"]
H --> I["Executable File"]
I --> J["Operating System Loading"]
J --> K["CPU Executes Machine Instructions"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style H fill:#F1F3F5,stroke:#C9D0D8,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
This is a common compilation process model. Different languages and toolchains may merge, adjust, or omit some stages.
1. Lexical Analysis: Identifying Words in Code
Lexical analysis is a fundamental stage in how a compiler processes source code.
The compiler splits source code into meaningful lexical units called tokens.
For example:
total = price + 100
A lexer can identify:
| Source code fragment | Token type |
|---|---|
total |
Identifier |
= |
Assignment operator |
price |
Identifier |
+ |
Addition operator |
100 |
Integer literal |
Lexical analysis focuses on: which valid symbols and words make up the code.
For example:
total = price + 100
is a set of recognizable tokens.
If unrecognized characters appear, or content does not conform to the language's lexical rules, the compiler may report a lexical error.
2. Syntax analysis: check whether the code structure is correct
Lexical analysis only knows which tokens are present; it does not know whether these tokens, when combined, conform to the language rules.
Syntax analysis is responsible for checking whether the arrangement of tokens conforms to the language's grammar.
For example:
if age >= 18:
print("成年人")
This is a conditional statement that conforms to Python syntax.
The following code, however, is missing a colon:
if age >= 18
print("成年人")
The compiler or interpreter will report a syntax error.
Syntax analysis usually builds an abstract syntax tree, or AST (Abstract Syntax Tree) for short.
For example:
total = price + quantity * 10
It can be abstracted into a structure similar to the following:
Assignment statement
├── Target variable: total
└── Expression
├── Left operand: price
├── Operator: +
└── Right operand
├── Left operand: quantity
├── Operator: *
└── Right operand: 10
This tree expresses operator precedence: first compute quantity * 10, then add it to price.
An AST is more suitable than the original source code for the compiler's subsequent analysis and transformation.
3. Semantic analysis: check whether the code has sensible meaning
Even if code is syntactically correct, that does not mean it is necessarily semantically valid.
For example:
int age = "hello";
In C, this code has a type mismatch, and the compiler usually provides diagnostic information.
Semantic analysis is responsible for checking whether code conforms to the language's semantic rules.
Common checks include:
- Whether variables have been declared.
- Whether variable scope is correct.
- Whether data types are compatible.
- Whether the arguments of a function call match.
- Whether the return value type meets requirements.
- Whether any access and usage rules specified by the language are violated.
For example:
int add(int a, int b) {
return a + b;
}
int result = add(10, 20);
The compiler can check whether the add function exists, whether the number of arguments is correct, and whether the types of the passed arguments are compatible.
Note that different languages vary in how strictly they perform type checking. Dynamically typed languages may defer some type checking until the program runs.
4. Intermediate representation: making it easier for the compiler to optimize code
Compilers usually do not generate final machine instructions directly from source code in one step.
Many modern compilers first convert code into an intermediate representation, or IR (Intermediate Representation) for short.
IR is a form of program representation between source code and target machine instructions.
For example:
int result = a + b * 2;
It can be converted into intermediate operations like the following:
t1 = b * 2
t2 = a + t1
result = t2
IR has several important advantages:
- Reduce coupling between the source language and the target processor.
- Facilitate optimizations such as constant propagation and dead code elimination.
- Allow one compiler to handle multiple source languages.
- Allow the same source language to generate code for multiple processor architectures.
For example, LLVM uses an intermediate representation to organize the compilation process.
LLVM IR example:
define i32 @add(i32 %a, i32 %b) {
entry:
%result = add i32 %a, %b
ret i32 %result
}
This is not final x86 or ARM machine instructions, but an intermediate representation used by LLVM.
5. Code optimization: make programs execute more efficiently
The compiler optimizes code under the premise of preserving program semantics.
For example:
int a = 10 * 20;
int b = a + 5;
The compiler can perform constant folding, computing in advance expressions that can be determined at compile time.
After optimization, it may conceptually become:
int a = 200;
int b = 205;
Common compiler optimizations include:
| Optimization Method | Purpose |
|---|---|
| Constant folding | Evaluate constant expressions in advance |
| Constant propagation | Propagate known constants into subsequent expressions |
| Dead code elimination | Remove code that does not affect the program's results |
| Common subexpression elimination | Avoid recomputing identical expressions |
| Loop optimization | Reduce redundant operations in loops |
| Inlining optimization | Expand some function calls at the call site |
| Register allocation | Use registers as much as possible to hold frequently accessed data |
Optimization does not mean that all programs will be faster.
Some optimizations may increase code size, compilation time, or memory consumption. The actual effect needs to be evaluated against the target platform and real workload.
6. Target Code Generation: Converting to Instructions the Processor Can Execute
The code generation stage converts the intermediate representation into target code according to the target processor architecture.
For example, the same simple addition logic can be compiled into different instructions for x86-64 or ARM64.
Conceptually:
High-level language:
result = a + b
Intermediate representation:
t1 = add a, b
Target assembly:
ADD register or memory operation for the corresponding architecture
The final generated target code may be:
- Assembly code.
- Object files.
- Machine code.
- WebAssembly bytecode.
- Other code formats recognized by virtual machines or runtimes.
A distinction must be made here: target code is not necessarily a complete executable program yet. It may still need to go through assembly, linking, and other stages.
7. Assembly and Linking: Generating a Loadable Program
In some traditional compiler toolchains, the compiler first generates assembly code, which is then converted into an object file by the assembler.
An object file usually contains:
- Machine instructions.
- Data segments.
- Symbol table.
- Relocation information.
- Debugging information.
A program may call functions in other files or system libraries, so a linker is also needed to perform symbol resolution and address relocation.
For example:
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}
Here, printf is not a function defined in the current source file. The linking stage needs to resolve its reference to the C standard library.
Linking can be divided into:
- Static linking: incorporate the required library code into the final executable.
- Dynamic linking: load the required shared libraries when the program runs.
Only after linking is complete can the operating system load the program according to the executable file format.
IV. How Does the CPU Execute Machine Instructions?
After source code has been compiled or interpreted, it must eventually enter the execution stage.
Taking common modern processors as an example, the CPU executes instructions according to the semantics specified by the instruction set architecture.
1. Basic Process of CPU Instruction Execution
The CPU execution process can be summarized as:
- Find the next instruction according to the program counter.
- Fetch the instruction from its storage location.
- Decode the instruction.
- Obtain the operands.
- Execute arithmetic, logic, or other operations.
- Write the result to a register or memory.
- Update the program counter and continue executing subsequent instructions.
This process is usually called the instruction cycle.
flowchart TD
A["Program Counter PC"] --> B["Instruction Fetch"]
B --> C["Instruction Decode"]
C --> D["Read Operands"]
D --> E["Execute Instruction"]
E --> F["Write Back Result"]
F --> G["Update PC"]
G --> B
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F3F5,stroke:#C9D0D8,color:#334155
Modern CPUs generally use techniques such as pipelining, out-of-order execution, branch prediction, and multiple issue, so the actual execution process is far more complex than this basic model.
2. What Is a Register?
Registers are high-speed storage units inside the CPU used to hold data and state.
For example, when performing addition, the CPU may first load the two operands into registers and then complete the calculation through the arithmetic logic unit.
Common registers include:
| Register | Purpose |
|---|---|
| General-purpose registers | Store integers, addresses, and temporary calculation results |
| Program counter PC | Store the location of the next instruction to be executed or related control state |
| Stack pointer SP | Point to the current stack position |
| Flags register | Store status flags generated by comparisons, operations, etc. |
| Vector registers | Support vector operations such as SIMD |
Register names, counts, and functions differ across processor architectures.
3. What is the ALU?
ALU (Arithmetic Logic Unit) is an important component in the CPU responsible for executing arithmetic and logical operations.
Common operations include:
- Addition and subtraction.
- Bitwise AND, bitwise OR, bitwise XOR.
- Comparison operations.
- Shift operations.
For example:
5 + 3 = 8
If an 8-bit binary representation is used:
00000101
00000011
--------
00001000
The ALU can perform the corresponding binary operations using digital circuits.
4. Why doesn't the CPU directly execute Python code?
Because Python's syntax and semantics are not part of the CPU instruction set.
For example:
print("Hello World")
The CPU does not recognize the Python function print, nor does it understand the language rules for string output.
Python programs need to be handled by the runtime system of a Python implementation.
The common CPython execution process can be simplified as:
flowchart TD
A["Python source code"] --> B["Lexical and syntax processing"]
B --> C["Generate AST"]
C --> D["Compile to Python bytecode"]
D --> E["Python virtual machine executes bytecode"]
E --> F["Call runtime and system interfaces"]
F --> G["Operating system and hardware perform operations"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F3F5,stroke:#C9D0D8,color:#334155
Pay special attention here:
Python bytecode is not native CPU machine instructions.
The CPython virtual machine is responsible for interpreting and executing Python bytecode; its underlying implementation itself is written in languages such as C and compiled into machine code.
When a program needs to output content, the Python runtime calls the corresponding underlying functionality, ultimately completing the actual operation through operating system interfaces.
V. What is the difference between compiled and interpreted languages?
Programming languages do not have only one execution method.
A common classification is compiled languages and interpreted languages, but this classification is not absolute. Modern languages may use compilation, interpretation, virtual machines, and just-in-time compilation technologies at the same time.
1. Compiled languages
Compiled languages usually use a compiler to convert source code into object code.
For example, C:
#include <stdio.h>
int main(void) {
int a = 10;
int b = 20;
printf("result = %d\n", a + b);
return 0;
}
In a Linux environment, you can use GCC to compile:
gcc main.c -o main
Execute the program:
./main
Basic process:
flowchart TD
A["C source code"] --> B["GCC compiler"]
B --> C["Object file"]
C --> D["Linker"]
D --> E["Executable file"]
E --> F["OS loads it"]
F --> G["CPU executes"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style G fill:#F1F3F5,stroke:#C9D0D8,color:#334155
Common characteristics of compiled languages:
- Machine code can usually be generated ahead of time.
- The compilation phase allows for more static checks and optimizations.
- The executable can run without the source code, but may depend on system libraries and the runtime environment.
- The target machine architecture and operating system can affect the program's compatibility.
Common examples include C, C++, Rust, and Go.
2. Interpreted Languages
Interpreted languages are usually read and executed by an interpreter or runtime environment.
For example, Python:
def add(a, b):
return a + b
print(add(10, 20))
Run:
python main.py
Take CPython as an example: it typically compiles the source code into bytecode, which is then executed by a virtual machine.
The basic process:
flowchart TD
A["Python source code"] --> B["Python interpreter"]
B --> C["Compile to bytecode"]
C --> D["Virtual machine executes"]
D --> E["Runtime calls low-level features"]
E --> F["Operating system and hardware"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style F fill:#F1F3F5,stroke:#C9D0D8,color:#334155
Interpreted languages typically have the following characteristics:
- Development and execution are relatively flexible.
- The runtime environment handles part of the program execution work.
- They can support dynamic typing and dynamic features.
- Performance depends on the interpreter, the runtime, and the specific optimization strategies.
Common examples include Python, Ruby, and PHP. JavaScript also has multiple execution mechanisms, such as interpreted execution and just-in-time compilation.
3. JIT Compilation: Combining Interpretation and Compilation
Modern runtimes often use JIT (Just-In-Time Compilation).
JIT compiles parts of the code into machine code while the program is running.
For example, a Java program typically goes through the following process:
flowchart TD
A["Java source code"] --> B["javac compiler"]
B --> C["Java bytecode"]
C --> D["JVM loads and executes"]
D --> E["Interpreted execution"]
D --> F["Runtime profiling"]
F --> G["JIT compiles hot code"]
G --> H["Native machine code"]
H --> I["CPU executes"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style C fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style D fill:#FFF1D6,stroke:#E6C77A,color:#70551C
style E fill:#F1F3F5,stroke:#C9D0D8,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
style H fill:#E8E2F8,stroke:#B6A6DF,color:#514477
style I fill:#FFF1D6,stroke:#E6C77A,color:#70551C
JIT can optimize hot code based on information collected at runtime, for example:
- Inline frequently called functions.
- Optimize type-stable operations.
- Reduce unnecessary dynamic checks.
- Optimize code based on actual execution behavior.
Therefore, interpreted and compiled are not two completely mutually exclusive execution modes.
4. Comparison of Three Execution Approaches
| Comparison Dimension | Traditional Compiled | Interpreted Execution | JIT |
|---|---|---|---|
| Primary Processing Timing | Before program execution | During program execution | During program execution |
| Typical Output | Machine code | Bytecode or program representation | Machine code |
| Runtime Dependency | Depends on the language and program | Usually requires an interpreter | Usually requires a runtime |
| Optimization Approach | Compile-time optimization | Interpreter optimization | Runtime optimization |
| Representative Technologies | GCC, Clang | CPython interpreted execution | JVM HotSpot, JavaScript JIT |
It cannot simply be assumed that compiled languages are necessarily faster than interpreted languages. Actual performance is also affected by factors such as algorithms, memory management, runtime implementation, compiler optimization, and hardware architecture.
Six: What Types of Programming Languages Are There?
Different programming languages have different design goals, so they differ in level of abstraction, execution mode, type system, and application scenarios.
1. Machine Language
Machine language is the instruction encoding that a processor can execute directly.
For example, a machine instruction may be represented in binary form as several bytes.
Its characteristics are:
- Closely tied to a specific processor instruction set.
- Can be executed directly by the processor.
- Expressing complex logic is very difficult.
- Usually incompatible across different processor architectures.
Programmers rarely use machine language directly to write large applications.
2. Assembly Language
Assembly language uses mnemonics to represent machine instructions.
For example:
mov eax, 10
mov ebx, 20
add eax, ebx
Assembly language is easier to read than binary machine code, but it still requires understanding processor registers, memory addressing, and instruction set rules.
Assembly programs are usually converted into machine code by an assembler.