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;
}
  1. AIt always returns 20, and the if test is removed
  2. BIt always returns 0, and return c * 2 is removed
  3. 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.
Practice this topic Back to topic

More Compilers questions

  1. What is the role of lexical analysis in a compiler?
  2. What is done during syntax analysis (parsing) in a compiler?
  3. Which is the best example of an error found during semantic analysis?
  4. Which describes an abstract syntax tree (AST)?
  5. What is the main advantage of using an intermediate representation (IR), independent of both source language and CPU, inside a compiler?