Consider the following code:
#include <iostream>
using namespace std;
int main()
{
int a=1,b=2;
if(a-- > 0 || ++b>2)
{
cout<< "Statement under if" <<endl;
}
else
{
cout<< "Statement under else"<<endl;
}
cout<< a << " " << b << endl;
return 0;
}
I was expecting Statement under if 0 3 as result. As value of a i.e, 1 is compared and then decremented while b is first incremented then compared. Since, 1 is greater than 0 and 3 is also greater than 2 hence both the conditions are true thus statement under if will be executed.
After that value of a will be 0 and b will be 3. So Output here should be "Statement under if 0 3".
But the actual output of the program is Statement under if 0 2.
I am unable to figure that how the actual output is different that of expected output.
>Solution :
This is happening due to what is known as "short-circuit expression evaluation".
The C language and all languages whose syntax is derived from C use this trick when evaluating boolean expressions: the evaluation of terms will stop as soon as the outcome can be known. So, since true || <anything> is true regardless of the value of <anything>, the <anything> term is not evaluated.
If you come from a Pascal background, you might find this a bit surprising.
It is a traditional thing, being done under some notion of performance, which might have been justified several decades ago, but only adds confusion today.