CSC376 · 2075 · 6 marks
Define three address codes. write three address codes for `S = do m = n + p while a <= b`
Define three address codes. write three address codes for S = do m = n + p while a <= b [6]
Three Address Code
Definition (Step 1 - Extract)
Given data (from the question):
- Statement to translate:
S = do m = n + p while a <= b - Structure: a
do ... whileloop with bodym = n + pand conditiona <= b.
No numeric matrices or values are involved; this is a compiler-design (intermediate code generation) problem.
Solution
Definition of Three Address Code
Three Address Code (TAC) is an intermediate code representation in which each instruction contains at most three addresses -- normally two operands and one result. The general form is:
$$x = y ; op ; z$$
where:
- $x, y, z$ are names, constants, or compiler-generated temporaries,
- $op$ is an operator (arithmetic, logical, relational, etc.).
It is called three address code because each statement references at most three "addresses." Complex expressions are broken into a sequence of such simple instructions using temporaries. TAC can be implemented using quadruples, triples, or indirect triples.
Common statement forms:
- Assignment:
x = y op z,x = op y,x = y - Unconditional jump:
goto L - Conditional jump:
if x relop y goto L - Labels:
L:
Translating: S = do m = n + p while a <= b
This is a do-while loop:
- Body:
m = n + p(executed at least once) - Condition:
a <= b(checked after each iteration; if true, repeat)
The body executes first, then the condition is tested. If the condition holds, control loops back to the beginning of the body.
Generated Three Address Code
| Line | Instruction | Meaning |
|---|---|---|
| 1 | L1: | Start of loop body (control always enters here first) |
| 2 | t1 = n + p | Evaluate n + p into temporary t1 |
| 3 | m = t1 | Assign result to m |
| 4 | if a <= b goto L1 | Test condition; if true, repeat the body |
| 5 | L2: | Exit point of the loop |
In pure sequential form:
L1: t1 = n + p
m = t1
if a <= b goto L1
L2: ...
Explanation
L1:marks the beginning of the body. Since it is ado-while, the body must run at least once, so control entersL1unconditionally.t1 = n + puses a new temporaryt1 = newtemp()to store the arithmetic result (three-address form: one operator, two operands, one result).m = t1completes the assignmentm = n + p.if a <= b goto L1evaluates the relational condition. If true, jump back toL1and repeat; if false, fall through.L2:is the loop-exit label, where execution continues after the loop.
Quadruple Representation (optional supporting form)
| # | op | arg1 | arg2 | result |
|---|---|---|---|---|
| (1) | + | n | p | t1 |
| (2) | = | t1 | - | m |
| (3) | if<= | a | b | L1 |
This confirms each instruction uses at most three addresses.
Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.