Compilers

After repeatedly applying constant propagation and constant folding to the code above, what does it finally become?

int n = 8;
int m = n * 2;
return m + 1;
  1. Areturn n * 2 + 1;
  2. Breturn 8 * 2 + m;
  3. Creturn 17;
Show answer and explanation

Answer: C. return 17;

Constant propagation sees that n holds 8 and never changes, so its uses become 8, giving m = 8 * 2. Constant folding computes 8 * 2 = 16, so m = 16, and further propagation and folding turn m + 1 into 16 + 1 = 17. The assignments to n and m are then unused and removed as dead code, leaving only return 17;. Forms that stop partway or substitute incorrectly are not the final result.

  • A. n is still present, so propagation is incomplete.
  • B. The substitution is wrong and the computation unfinished.
  • C. Correct. It proceeds 8 → 16 → 17, leaving only a constant.
Practice this topic Back to topic

More Compilers questions

  1. Which describes applying common subexpression elimination to the code above?
  2. What does dead-code elimination remove?
  3. Which pair gives the advantage and drawback of function inlining?
  4. What is the main effect of loop unrolling?
  5. In the loop above, which computation is a candidate for loop-invariant code motion (hoisting out of the loop)? (Assume x and y are not modified in the loop.)