Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

false || true giving 0 in MinGW Compiler v 6.3.0-1

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.

like image 657
darkavenger Avatar asked Jan 30 '23 02:01

darkavenger


1 Answers

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);.

like image 193
songyuanyao Avatar answered Feb 05 '23 15:02

songyuanyao