0
0
Compiler-designConceptBeginner · 3 min read

What is Three Address Code in Compilers: Explanation and Example

Three address code is an intermediate representation used in compilers where each instruction has at most three addresses or operands. It simplifies complex expressions into simple steps, making it easier for the compiler to optimize and generate machine code.
⚙️

How It Works

Three address code breaks down complex operations into simple instructions, each involving at most three parts: two inputs and one output. Think of it like writing a recipe where each step only uses a few ingredients and produces one result, making the process clear and easy to follow.

For example, instead of calculating a = b + c * d in one step, three address code splits it into smaller steps like multiplying c and d first, storing the result, then adding b. This step-by-step approach helps the compiler understand and optimize the code better.

💻

Example

This example shows how the expression a = b + c * d is translated into three address code instructions.

plaintext
t1 = c * d
t2 = b + t1
a = t2
Output
t1 holds the product of c and d t2 holds the sum of b and t1 a is assigned the value of t2
🎯

When to Use

Three address code is used inside compilers during the translation of high-level programming languages to machine code. It helps by simplifying expressions and making the code easier to analyze and optimize. This intermediate step is crucial for tasks like detecting common subexpressions, reordering instructions, and improving performance.

In real-world compiler design, three address code acts as a bridge between the source code and the final machine instructions, enabling better control over how the program runs on hardware.

Key Points

  • Each instruction has at most three operands: two inputs and one output.
  • It simplifies complex expressions into smaller, manageable steps.
  • Used as an intermediate step in compilers for optimization and code generation.
  • Helps in detecting and eliminating redundant calculations.

Key Takeaways

Three address code breaks complex expressions into simple instructions with up to three operands.
It is an intermediate representation used by compilers to optimize and generate machine code.
Each instruction typically involves two input values and one output variable.
This approach makes code analysis and optimization easier and more effective.