Why is the output of the type bool equal to 0 in this case?

Viewed 68
#include <iostream>
#include <cmath>
using namespace std;

int
main ()
{
  cout << ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3);
  cout << ('x' > 0xFF);
  cout << (3 * 5 < 35) && (53 > 5 * 3);
  return 0;
}

I get 001 even though it should be 101 as far as I understand.

1 Answers

According to C++ operator precedence, << has higher precedence than || and &&. So

cout << ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3);

is actually parsed as (extra spaces added for emphasis)

( cout << ('x' > 0xFF) )    || (3 * 5 < 35) && (53 > 5 * 3);

It's printing out the result of 'x' > 0xFF (which is false) and basically ignoring the rest. To get what you want, you need to wrap it in parentheses:

cout <<    ( ('x' > 0xFF) || (3 * 5 < 35) && (53 > 5 * 3) );

As to why (cout << A) || B is valid in the first place, std::basic_ostream (of which cout is an instance) has the following overloads:

  1. operator<< - writes the data to the stream and returns a reference to the stream (that's what lets you chain multiple calls together).
  2. operator bool - returns whether the stream is still valid.

So (cout << A) || B is syntactic sugar for static_cast<bool>(cout.operator<<(A)) || B

Related