0

why is the value of the following expression false?

bool a = false;
bool b= true;
std::cout<< a || !b && !a || b;

and why does the value changes when adding parenthesis

bool a = false;
bool b= true;

std::cout<< (a || !b && !a || b);

Shouldn't the parenthesis be putted like this:

a || (!b && !a) || b

, and the result be false or false or true equal true?

1 Answers1

0

As already mentioned in comments, in the first case, the expression is due to operator precedence evaluated as

(std::cout << a) || !b && !a || b;

Result of std::cout << a is a reference to the std::cout object itself, which is in C++03 convertible to bool through operator void*() inherited from std::basic_ios. In C++11, there is operator bool() instead, which allows so-called contextual conversion.

The rest is therefore just a boolean expression and its result is discarded.

Daniel Langr
  • 20,369
  • 3
  • 44
  • 81