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

Logical operators don't output correct results

Here is the code that I’m struggling with

#include <iostream>
#include <string>

using namespace std;

int main() {
    int a{ 6 }, b{ 9 };
    cout << !(a < 5) && !(b >= 7);
}

Every time I run this code it outputs 1. Why doesn’t it output 0?

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 :

You’ve been tripped up by the semantic overloading we give the << operator in C++.

This operator comes from C, where it is used exclusively for bit-shifting integers.

Because of that, it has a lower precedence than the && operator. C++’s use of the << operator for stream insertion doesn’t change that. The << will be evaluated before the &&.

Thus

cout << !(a < 5) && !(b >= 7);

first inserts !(a<5) (true, since a==6) into the stream, printing a 1. Then it evaluates the return value of that (a reference to cout), converts it to boolean, then evaluates the && (essentally (!cout.fail() && !(b>=7))), discarding the result.

You need more parentheses:

cout << (!(a < 5) && !(b >= 7));

However,

cout << (a>=5 && b < 7);

would be clearer.

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