1.2.4 Booleans

Like other computer languages, Booleans are true/false variables. They work very much like any other computer languages but do have one aspect a little different than a language such as Java.

In C++, Booleans are declared as type bool. They can be declared and initialized or just declared, just like other variables that you saw in C++.

bool b1 = true;

bool b2;
b2 = false;

The one thing that is a little different compared to Java is that Booleans are stored and printed as either a 1 or 0. (1 for true).

cout << b1 << endl; // true = 1

You can actually assign them values of 1 and 0 as well, but true and false will work for the definition.

Logical Operators

Like Java and other languages, C++ makes use of logical operators for Booleans. See the table below.

OperatorDescription

&&

And operator. If both values are true, returns true, otherwise returns false.

||

Or operator. If either value is true, returns true, otherwise returns false.

!

Not operator. Returns the opposite value. For example, if true, returns false.

Try This Example

Last updated