'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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
