Compilers

Which is an example of constant folding by a compiler?

  1. AMerging repeated calls to the same function into a single call
  2. BComputing x = 3 * 4 at compile time to produce x = 12
  3. CReplicating a loop body four times to reduce the number of iterations
Show answer and explanation

Answer: B. Computing x = 3 * 4 at compile time to produce x = 12

Constant folding evaluates expressions whose values are fixed at compile time and replaces them with the resulting constants. 3 * 4 always yields 12, so there is no need to multiply at run time. Combined with constant propagation, computations through variables can be folded as well. There are caveats, such as matching rounding behavior for floating point. Replicating a loop body is loop unrolling, and merging function calls is a different optimization.

  • A. Merging function calls is not constant folding.
  • B. Correct. It precomputes expressions with known values.
  • C. Replicating the body is loop unrolling.
Practice this topic Back to topic

More Compilers questions

  1. After repeatedly applying constant propagation and constant folding to the code above, what does it finally become?
  2. Which describes applying common subexpression elimination to the code above?
  3. What does dead-code elimination remove?
  4. Which pair gives the advantage and drawback of function inlining?
  5. What is the main effect of loop unrolling?