Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C++) Why does the '||' logical operator gives back 1? [duplicate]

Tags:

c++

I'm a beginner in C++. Why does this code gives me back '1' when I write it out?

cout << (false||(!false));

It writes out '1', which is equivalent with 'true'.

Why does it give back true instead of false? How does it decide whether the statement is true or not?

like image 915
tibiv111 Avatar asked Nov 29 '22 05:11

tibiv111


2 Answers

How does it decide whether the statement is true or not?

The boolean operators follow the rules of boolean algebra.

The ! operator (not) corresponds to logical negation. Result is false if operand is true and true if operand is false.

The || (inclusive or) operator corresponds to logical (inclusive) disjunction. The result is false only if both operands are false. Otherwise result is true.

The output is 1, because the standard output stream produces the character 1 when you insert a true bool (unless the std::ios_base::boolalpha format flag is set).

like image 164
eerorika Avatar answered Dec 18 '22 07:12

eerorika


This:

cout << (false||(!false));

Evaluates to:

cout << (false||(true));

Which evaluates to:

cout << true;

Since false || true is true. The C++ representation of true is generally 1, as opposed to 0 for false, at least by convention.

like image 43
tadman Avatar answered Dec 18 '22 08:12

tadman