Although Java has the rule that the left operand of every binary operator is eva
ID: 3561755 • Letter: A
Question
Although Java has the rule that the left operand of every binary operator is evaluated before the right operand, most languages give the compiler the freedom to choose which operand is evaluated first. When expressions have side effects, the value of the expression can be different depending upon which order is used. Give an example in C++ of an expression whose value depends upon the evaluation order. Show the orders that produce different values and the values they produce. Explain what side effect is the expression contains.
Explanation / Answer
Java has the rule that the left-hand operand of a binary operator appears to be fully evaluated, before the
part of a right-hand operand is evaluated.if left-hand operand contains assignment to variable and the right-hand operand contains a referenceto same the variable, then the value produced by its reference it will reflect the fact that assignment occurred first.
example1:
class Test {
public static void main(String[] args) {
int k = 2;
int l = (k=3) * k;
System.out.println(l);
}
}
ouput:
prints 9
example2:
class Test {
public static void main(String[] args) {
int i = 9;
i += (i = 3);
System.out.println(i);
int j = 9;
j = j + (j = 3);
System.out.println(j);
}
}
output:
prints
12
12
C++ expression for whose value depends on the evaluation order .below is the example for produce different values.
example1: (multiplication table with post increment in expression)
using namespace std;
int main()
int result12, j= 1;
int value11 = 2;
while( j <= 10 )
result12 = value11 * j++ ;
cout << value11 << " * " << (j-1) << " = " << result12 << endl;
system(“pause”);
return 0;
}
example2:(multiplication table with pre increment in expression)
using namespace std;
int main()
int result12, j= 1;
int value11 = 2;
while( j <= 10 )
result12 = value11 * ++j ;
cout << value 11<< " * " << (j-1) << " = " << result12 << endl;
system(“pause”);
return 0;
}
There is no side effects expression contains it always returns same output with same input values.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.