Home > OS >  Logical operators don't output correct results
Logical operators don't output correct results

Time:04-14

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?

CodePudding user response:

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.

  • Related