Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 949
Oleksandr Novik Avatar asked Aug 03 '21 07:08

Oleksandr Novik


People also ask

Why in JS [] == this is true?

Double equals, == , performs an amount of type coercion on values before attempting to check for equality. So arr == arr returns true as you'd expect as what you are actually checking is if [] == [] and both sides of the equation are of the same type.

Does true mean 1?

Boolean Variables and Data Type ( or lack thereof in C ) C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

What is false && false?

If the left side of the expression is "falsey", the expression will return the left side. If the left side of the expression is "truthy", the expression will return the right side. That's it. So in false && false , the left side is "falsey", so the expression returns the left side, false .


Video Answer


2 Answers

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);
like image 140
songyuanyao Avatar answered Oct 16 '22 11:10

songyuanyao


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 
like image 28
rawrex Avatar answered Oct 16 '22 13:10

rawrex