I was playing around with booleans and ended up with this line of code:
std::cout << true && false;
which, for some reason, produces 1. How is this possible, if && requires both sides to be true, in order to produce 1?
I was playing around with booleans and ended up with this line of code:
std::cout << true && false;
which, for some reason, produces 1. How is this possible, if && requires both sides to be true, in order to produce 1?
Because operator<< has higher precedence than operator&&, std::cout << true && false; is just same as (std::cout << true) && false; (i.e. print out true firstly, then the returned std::cout is converted to bool, which is used as operand with false for the operator&&, the result is discarded at last).
Note that std::cout could be converted to bool via operator bool, which could be used in contextual conversions (including as operand of built-in operator&&) even it's marked as explicit.
Returns
trueif the stream has no errors and is ready for I/O operations. Specifically, returns!fail().
You might specify precedence by adding parentheses.
std::cout << (true && false);
Due to operator precedence, the true is printed and then the return of the operator<< (the std::cout) is && with the false.
(std::cout << true) && false; // Equivalent