CSC376 · 2078 · 5 marks
Define three address codes. Write down Quadruples for: a = -b*(c+d)/e.
Define three address codes. Write down Quadruples for: $a = -b*(c+d)/e$. [5]
Three Address Code and Quadruples
Given
- Expression to translate: $a = -b * (c + d) / e$
- Required output format: Quadruples
- Also required: Definition of three address code
No numeric data is involved; this is a code-generation problem. All required information is present.
Solution
Definition of Three Address Code
Three address code (TAC) is an intermediate representation of a program in which each statement contains at most three addresses (or operands): two for the operands and one for the result. The general form is:
$$x = y ; \text{op} ; z$$
where $x$, $y$, $z$ are names, constants, or compiler-generated temporary variables, and $\text{op}$ is an operator (arithmetic, logical, etc.). Each statement performs at most one operation, which makes it easy to translate into machine code and to optimize.
Three address code can be implemented in three ways: Quadruples, Triples, and Indirect Triples.
Breaking the Expression into Three-Address Statements
Expression: $a = -b * (c + d) / e$
Applying operator precedence (parentheses first, then unary minus, then $*$ and $/$ left to right):
| Step | Statement | Explanation |
|---|---|---|
| 1 | $t_1 = -b$ | unary minus on $b$ |
| 2 | $t_2 = c + d$ | evaluate parenthesis |
| 3 | $t_3 = t_1 * t_2$ | multiply |
| 4 | $t_4 = t_3 / e$ | divide by $e$ |
| 5 | $a = t_4$ | assign to $a$ |
Quadruple Representation
A quadruple has four fields: (op, arg1, arg2, result).
| Index | op | arg1 | arg2 | result |
|---|---|---|---|---|
| (0) | uminus | b | _ | $t_1$ |
| (1) | + | c | d | $t_2$ |
| (2) | * | $t_1$ | $t_2$ | $t_3$ |
| (3) | / | $t_3$ | e | $t_4$ |
| (4) | = | $t_4$ | _ | a |
Notes:
uminusdenotes the unary minus operator (distinguished from binary subtraction)._indicates an unused field.
Final Result
The expression $a = -b*(c+d)/e$ produces 5 quadruples using 4 temporary variables ($t_1, t_2, t_3, t_4$), matching the standard textbook decomposition.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.