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?

  • 2
    Read about [*operator precedence*](http://en.cppreference.com/w/cpp/language/operator_precedence) in [any good beginners book](https://stackoverflow.com/a/388282/440558). And remember that `<<` is really the *left bitwise shift* operator. – Some programmer dude Jan 21 '18 at 15:49
  • 2
    See the [compiler warnings](http://coliru.stacked-crooked.com/a/32322c6b4b38148e) you'll get with that code. –  Jan 21 '18 at 15:50
  • && has an higher precedence than ||, so the value should be true. – Pablito Escobar Jan 21 '18 at 15:54
  • 2
    Seems like you either didn't read or didn't understand the comments. `<<` has even higher precendence, so the first code is interpreted as `(std::cout<< a) || !b && !a || b`. – JJJ Jan 21 '18 at 15:58
  • ok now I've got it thank you – Pablito Escobar Jan 21 '18 at 16:00
  • http://en.cppreference.com/w/cpp/language/operator_precedence – Jesper Juhl Jan 21 '18 at 16:04

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
  • 22,196
  • 3
  • 50
  • 93