Consider the following program: int gate(int rank) { int i; for (i = 1; i <…
Consider the following program:
int gate(int rank)
{
int i;
for (i = 1; i < 10; i++)
printf("Gate rank = %d", rank);
return 1;
}
Which of the following code optimization can be applied on the above C-code?
Answer: C. Loop unrolling — Answer: Loop unrolling is the appropriate optimization. Why: The loop runs a fixed number of times (from i = 1 to i < 10, so 9 iterations) and each iteration…
- A.
Code motion on loop invariant
- B.
Strength reduction
- C.
Loop unrolling
- D.
None of these
Attempted by 92 students.
Show answer & explanation
Correct answer: C
Answer: Loop unrolling is the appropriate optimization.
Why: The loop runs a fixed number of times (from i = 1 to i < 10, so 9 iterations) and each iteration performs the same printf call using the unchanged parameter rank. Unrolling reduces the loop-control overhead (increment, comparison, branch) by replicating the loop body multiple times.
Example (manual full unroll):
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
Example (partial unroll):
for (i = 1; i < 10; i += 3) {
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
printf("Gate rank = %d", rank);
/* handle remaining iterations if needed */
Why code motion is not appropriate here: Code motion (hoisting) is only safe for loop-invariant code that has no side effects. The printf call has an observable side effect (it prints each iteration), so hoisting it outside the loop would change program behavior.
Why strength reduction is not appropriate here: Strength reduction targets expensive arithmetic operations (e.g., replacing multiplication with addition when updating an index). This loop uses a simple increment and has no such expensive operations to reduce.
Compiler note: Modern compilers can automatically perform loop unrolling (full or partial) when the trip count is known or when guided by optimization flags.