180k views
5 votes
Question 1:

Suppose that we are using C++-like syntax. Read the following
code segment.
int i = 0;
int func(int& k)
{ k += (-5);
i += 4;
return 2 * k + i +1;
}
int main(void)
{
int i = 5;

int j = 10;

int sum1, sum2, sum3;

sum1 = (i/2) + func(i) ; sum2 = i + j + func(j) * func(j) + func(i); sum3 = func(i) + i + 2 * func(i);

}
What are the values of sum1, sum2 and sum3, if the operands in expressions are evaluated from left to right and we use the normal precedence for evaluating an expression, e.g. * has a precedence than +? What are the values of sum1, sum2 and sum3, if the operands in all the expressions (inlcuding the expressions in func(…)) are evaluated from right to left and we use the normal precedence for evaluating an expression, e.g. * has a precedence than +?

1 Answer

3 votes

Final answer:

sum1 = 12, sum2 = 50, sum3 = -10 when operands are evaluated from left to right. sum1 = 12, sum2 = 50, sum3 = -13 when operands are evaluated from right to left.

Step-by-step explanation:

To determine the values of sum1, sum2, and sum3, let's evaluate the code segment using the given conditions.

If operands are evaluated from left to right:

sum1 = (i/2) + func(i)
sum1 = (5/2) + func(5)
sum1 = 2 + 10
sum1 = 12

sum2 = i + j + func(j) * func(j) + func(i)
sum2 = 5 + 10 + func(10) * func(10) + func(5)
sum2 = 5 + 10 + (-5) * (-5) + 10
sum2 = 5 + 10 + 25 + 10
sum2 = 50

sum3 = func(i) + i + 2 * func(i)
sum3 = func(5) + 5 + 2 * func(5)
sum3 = (-5) + 5 + 2 * (-5)
sum3 = (-5) + 5 + (-10)
sum3 = -10

If operands are evaluated from right to left:

sum1 = (i/2) + func(i)
sum1 = (5/2) + func(2)
sum1 = 2 + 10
sum1 = 12

sum2 = i + j + func(j) * func(j) + func(i)
sum2 = 5 + 10 + func(10) * func(10) + func(2)
sum2 = 5 + 10 + (-5) * (-5) + 10
sum2 = 5 + 10 + 25 + 10
sum2 = 50

sum3 = func(i) + i + 2 * func(i)
sum3 = func(2) + 2 + 2 * func(5)
sum3 = (-5) + 2 + 2 * (-5)
sum3 = (-5) + 2 + (-10)
sum3 = -13

User Leszek P
by
7.7k points