Compilers
In the code above, which optimization applies after inlining sq, and with what result?
static int sq(int v) { return v * v; }
int g(void) { return sq(6) + 1; }
- ACommon subexpression elimination makes g call sq twice
- BConstant folding reduces g to code that simply returns 37
- CLoop unrolling replaces v * v with six additions
Show answer and explanation
Answer: B. Constant folding reduces g to code that simply returns 37
Inlining sq turns g into return 6 * 6 + 1;, so every operand of the multiplication is a constant. Constant folding then computes 6 * 6 = 36 and 36 + 1 = 37, reducing g to code that just returns 37. Beyond removing call overhead, a major benefit of inlining is enabling such optimizations using the caller's values. There is no loop here, and g does not end up calling sq twice.
- A. The call actually disappears.
- B. Correct. After inlining, constant folding leaves just 37.
- C. There is no loop in this code.