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

cout unexpected print result with logical OR operator

Why does this code print 0?

#include <iostream>

using namespace std;

int main()
{
    cout<< 0 || 7;

    return 0;
}

In Javascript, the result of that operation would be 7.

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

>Solution :

Due to Operator Precedence, << has a higher precedence than ||, so the compiler implicitly interprets cout << 0 || 7 as-if you had written (cout << 0) || 7. To process || first, you need to use your own parenthesis to tell the compiler that you want cout << (0 || 7) instead.

However, this will output 1, not 7 as you are expecting, because C++’s logical OR returns an integer 1 if either operand evaluate to a non-zero value, otherwise it returns an integer 0 instead. Unlike Javascript’s logical OR, which returns the actual value of the first operand that is not equal to zero.

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