In: Computer Science
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.
In C++, the expression is checked in such a way that the checking starts from the left hand side then move to the right hand side.
With the operators such as &&, ||, if there is no requirement only one side gets evaluated. Example of && operator. If the first condition becomes false, there is no need to check the second condition.
Ex1:
#include <iostream>
using namespace std;
int main() {
int a = 0;
int b = 0;
if(a == 0 && b++ > 0)
{
}
cout << "a = " << a << " b = " << b << endl;
}
Explanation:
Ex2:
#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 0;
if(a == 0 && b++ > 0)
{
}
cout << "a = " << a << " b = " << b << endl;
}
Explanation:
For the operator ||, if the first condition becomes true, there is no requirement for checking the second condition.
And if the first condition becomes false, it checks the second condition and if it is true then the whole statement considered to be true.
Ex1:
#include <iostream>
using namespace std;
int main() {
int a = 0;
int b = 0;
if(a == 0 || b++ > 0)
{
}
cout << "a = " << a << " b = " << b << endl;
}
Explanation:
Ex2:
#include <iostream>
using namespace std;
int main() {
int a = 1;
int b = 0;
if(a == 0 || b++ > 0)
{
}
cout << "a = " << a << " b = " << b << endl;
}
Explanation: