Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the second term of my boolean expression not being evaluated?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading