Compilers
Which is an example of constant folding by a compiler?
- AMerging repeated calls to the same function into a single call
- BComputing x = 3 * 4 at compile time to produce x = 12
- 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.