Why is true && false equal to 1 in C++?
Asked Answered
R

2

9

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?

Recover answered 3/8, 2021 at 7:49 Comment(8)
Because its actually seen by the compiler as (std::cout << true ) then the function result is ANDed with false and the result discarded. Use Brackets to avoid operator precedence issues en.cppreference.com/w/cpp/language/operator_precedence eg std::cout<< (true && false)Canalize
IMO, the design decision regarding the precedence of the C << and >> operators was a sad mistake.Harwin
The precedence of << operator is greater than that of && so the expression is same as (std::cout << true) && false and it's valid because std::cout which is std::basic_ostream object has a bool conversion operator. So essentially it boils down to static_cast<bool>((std::cout << true)) && falseWhang
@YvesDaoust -- in C, the precedence does what's expected. The problem in C++ is that << and >> are overloaded for use with streams, and the precedence that works in mixed arithmetic/logical expressions doesn't work well for stream operations.Goblet
@PeteBecker: no, you don't get it. a << b + c should mean (a << b) + c, not a << (b + c). This is a mistake of K & R.Harwin
@YvesDaoust I disagree. a << b + c should be invalid. Mixing unparenthesised operators is a mistakeGalateah
@YvesDaoust Not bad faith. I'd disallow that too. I'd disallow a - b - c as well, not all operators form (semi)groupsGalateah
@Caleth: the point is not what you would do (such as rejecting centuries of math notation). The point is that K & R made a design mistake.Harwin
R
13

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 true if 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);
Rombert answered 3/8, 2021 at 7:51 Comment(0)
M
6

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 
Mortgage answered 3/8, 2021 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.