Compilers
After thoroughly applying constant propagation, constant folding and dead-code elimination to the function above, what does it return and what code remains?
int h(void) {
int a = 5;
int b = a * 3;
int c = b - a;
if (c > 100) return 0;
return c * 2;
}
- AIt always returns 20, and the if test is removed
- BIt always returns 0, and return c * 2 is removed
- CAll computation remains, and it returns 20 or 0 at run time
Show answer and explanation
Answer: A. It always returns 20, and the if test is removed
Propagating a = 5 folds b = 5 * 3 = 15 and c = 15 − 5 = 10. The condition c > 100 becomes 10 > 100, always false, so the return 0 branch can never execute and is removed as dead code. The remaining return c * 2 becomes 10 × 2 = 20, leaving just return 20;. Since the condition is always false, it never returns 0, and no run-time computation or test is needed.
- A. Correct. c = 10 makes the condition always false, leaving code that returns 20.
- B. The condition is always false, so it never returns 0.
- C. Everything is determined by constants, so no run-time computation remains.