A compiler is a special program that translates a source program written in a high-level programming language (like C, Java) into a target program in machine code (executable format).
The compiler ensures the translated program performs the same tasks as the source code, but in a way understandable by the computer.
Working of a Compiler (Structure of a Compiler):
The working of a compiler is divided into two main parts:
- Analysis Phase (Front-end) – Analyzes the source code and checks for errors.
- Synthesis Phase (Back-end) – Translates the analyzed code into target machine code.
Each part has multiple phases, as shown below:
Phases of a Compiler:
| Phase | Description |
|---|---|
| 1. Lexical Analysis | Breaks input into tokens. Example: a = b + 2 → (id,1) (=) (id,2) (+) (num,2) |
| 2. Syntax Analysis | Creates a syntax tree (or parse tree) using tokens to represent grammar. |
| 3. Semantic Analysis | Ensures semantic correctness. Example: checks type mismatches. |
| 4. Intermediate Code Generation | Translates source code into an intermediate representation (e.g., 3-address code). |
| 5. Code Optimization | Improves intermediate code (e.g., removes redundant instructions). |
| 6. Code Generation | Produces final machine code from optimized intermediate code. |
| 7. Symbol Table Management | Maintains information about variables, their types, scope, etc. |

Example:
position = initial + rate * 60;

