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; }
  1. ACommon subexpression elimination makes g call sq twice
  2. BConstant folding reduces g to code that simply returns 37
  3. 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.
Practice this topic Back to topic

More Compilers questions

  1. Which describes software pipelining?
  2. Why does a compiler with strict settings not reorder the floating-point sum (a + b) + c into a + (b + c) on its own?
  3. Which kind of instruction does a compiler's automatic vectorization use?
  4. What basic condition must compiler optimizations respect?
  5. Which describes instruction selection, one stage of code generation?