1

When printing to the terminal, the OR operator is not being applied in C++.

MWE:

#include <iostream>
int main()
{
    std::cout << false || true;
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Hans
  • 224
  • 2
  • 13

1 Answers1

3

Shift operators have higher priority than logical operators.

So this statement

std::cout << false || true;

is equivalent to

( std::cout << false ) || ( true );

As a result the literal false will be outputted as integer 0.

If you want to output the literal true then you should write

std::cout << ( false || true );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    The answer is correct. To a novice the operator precedence in this case is probably surprising. If the `<<` operator was invented as a streaming operator it would have had lower precedence, but its original and alternative use as a bit-shift operator means that it has the precedence that it has. This is a general issue with operator overloading. As the answer illustrates, better use too many parenthesis than too few. I often put redundant parenthesis so that code can be understood without cross-checking the precedence table. – nielsen Feb 10 '23 at 22:58