Consider the following ANSI C code segment: z=x + 3 + y->f1 + y->f2; for (i =…
2021
Consider the following ANSI C code segment:
z=x + 3 + y->f1 + y->f2;
for (i = 0; i < 200; i = i + 2) {
if (z > i){
p = p + x + 3;
q = q + y->f1;
} else {
p = p + y->f2;
q = q + x + 3;
}
}
Assume that the variable y points to a struct (allocated on the heap) containing two fields \(f1\) and \(f2\), and the local variables x, y, z, p, q, and i are allotted registers. Common sub-expression elimination (CSE) optimization is applied on the code. The number of addition and the dereference operations (of the form y ->\(f1\) or y ->\(f2\)) in the optimized code, respectively, are:
- A.
403 and 102
- B.
203 and 2
- C.
303 and 102
- D.
303 and 2
Attempted by 66 students.
Show answer & explanation
Correct answer: D
Solution: Count additions and dereferences after applying common subexpression elimination and hoisting of loop-invariant expressions.
Initial computation (before the loop):
Compute x+3 once: 1 addition.
Load y->f1 and y->f2 once each (hoisted): 2 dereferences.
Compute z = (x+3) + f1 + f2 requires 2 more additions.
Adds from initial computation: 1 (x+3) + 2 (to form z) = 3 additions; dereferences so far = 2.
Loop work:
Number of iterations: i runs from 0 to 198 by 2 → 100 iterations.
Per iteration operations (after hoisting):
p = p + (x+3) → 1 addition
q = q + (y->f1 or x+3) → 1 addition
i = i + 2 (loop increment) → 1 addition
Total per iteration additions = 3. For 100 iterations → 300 additions.
Total counts and final answer:
Total additions = initial 3 + loop 300 = 303 additions.
Total dereferences = 2 (y->f1 and y->f2 loaded once).
A video solution is available for this question — log in and enroll to watch it.