Consider the following C code segment.
for (i = 0, i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i%2)
{
x += (4*j + 5*i);
y += (7 + 4*j);
}
}
}
Which one of the following is false?
View worked solution
Answer: D
To determine which statement is false, let's analyze each optimization technique with respect to the given code segment:
- Loop Invariant Computation (Option A is True): An expression is loop-invariant if its value does not change during the execution of the loop.
- In the inner loop (with loop variable ), the expression
5*iand the conditioni%2depend only on . - Since is constant relative to the inner loop, these computations can be hoisted outside the inner loop.
- In the inner loop (with loop variable ), the expression
- Common Sub-expression Elimination (Option B is True): An occurrence of an expression is a common sub-expression if it was previously computed and the values of its operands have not changed since.
- The expression
4*jis computed twice within the same iteration: once inx += (4*j + 5*i)and again iny += (7 + 4*j). - We can compute
temp = 4*jonce and reuse it.
- The expression
- Strength Reduction (Option C is True): Strength reduction replaces expensive operations (like multiplication) with cheaper ones (like addition) using induction variables.
- The multiplication
4*jcan be replaced by initializing a temporary variable to0and adding4in each iteration of the -loop.
- The multiplication
- Dead Code Elimination (Option D is False): Dead code is code that is either unreachable or computes a value that is never used.
- All statements inside the loops are reachable and actively update the variables
xandy. There is no dead code present in this segment.
- All statements inside the loops are reachable and actively update the variables
Therefore, statement D is false.
Free practice · Your answers on this page are not saved.
