4

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?

tibiv111
  • 105
  • 8

4 Answers4

10

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).

eerorika
  • 232,697
  • 12
  • 197
  • 326
7

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • 3
    This is not about machine representations. The bit representation of `true` is up to the implementation. The standard, however, mandates that you get a `1` when you _convert_ a bool to an int. – Lightness Races in Orbit Oct 07 '19 at 16:58
  • @LightnessRacesinOrbit Perhaps I used that term too loosely, so that's a good clarification. – tadman Oct 07 '19 at 16:59
  • It's still misleading, unfortunately! The _representation_ could be 97437652, per C++. – Lightness Races in Orbit Oct 07 '19 at 17:01
  • @LightnessRacesinOrbit Would "generally" suffice? I've never seen it as anything but, yet you're right, someone could get...creative. – tadman Oct 07 '19 at 17:15
  • It would be easier to just make a statement about bool converting to int (see how eerorika did it), but your answer is now at least factually correct, thanks :) – Lightness Races in Orbit Oct 07 '19 at 17:26
  • 2
    @LightnessRacesinOrbit There's technically no conversion to int involved in the example. There is an overload for inserting the bool directly. The implementor may of course take advantage of the conversion rule when implementing the stream operation. – eerorika Oct 07 '19 at 17:30
  • @eerorika You speak the truth – Lightness Races in Orbit Oct 07 '19 at 17:32
5

Because false or not false is true.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
2

Think about your if statement ...

Your test value is a boolean so it is either true or false. Now look at your if:

if (false || (!false))

You are saying:

The test result is true if:

  1. The test value is false or
  2. The test value is not false (thus true).

So either way, the if returns true whether it is true or false.

Community
  • 1
  • 1
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164