This is a C++ program I wrote:
#include <iostream>
using namespace std;
int main() {
cout << "\n" << "false || false" << ": " << false || false;
cout << "\n" << "false || true" << ": " << false || true;
cout << "\n" << "true || false" << ": " << true || false;
cout << "\n" << "true || true" << ": " << true || true;
cout << "\n" << "false && false" << ": " << false && false;
cout << "\n" << "false && true" << ": " << false && true;
cout << "\n" << "true && false" << ": " << true && false;
cout << "\n" << "true && true" << ": " << true && true;
return 0;
}
and this is the output.
false || false: 0
false || true: 0
true || false: 1
true || true: 1
false && false: 0
false && true: 0
true && false: 1
true && true: 1
Could someone explain to me why false || true
is giving 0
? I am using MinGW C++ Compiler version 6.3.0-1.
According to C++ Operator Precedence, operator<<
has higher precedence than operator ||
(and operator &&
), so cout << false || true;
will be interpreted as if (cout << false) || true;
; you'll always get false
to be printed out.
To solve the issue you should add parentheses to specify the precedence explicitly, e.g. cout << (false || true);
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With