Booleans - true and false values

An overview of the fundamental true or false data type, how we can create them, and how we can combine them.

Ryan McCombe
Updated

In this lesson, we introduce the concept of booleans in C++. Booleans are one of the simplest yet most powerful data types in programming. They represent the concept of binary states - true or false. You can think of them as the answer to a yes-or-no question.

Understanding Booleans is crucial because they form the backbone of decision-making in code. They help us answer questions like: "Is this condition met?" or "Should this action be performed?"

They are the key to controlling how a program behaves and responds to different scenarios. We've already seen a glimpse of how we can create booleans:

bool isAlive { true };
bool isDead { false };

In this lesson, we'll explore more on how to create, manipulate, and use these fundamental types to direct the flow of our programs. We'll start with the basics of creating booleans through comparisons and then move on to more complex operations.

Creating Booleans by Comparing Numbers

One of the main ways we create booleans is by using specific operators on other data types, particularly numbers.

Two sequential equals characters, the == operator, allows us to compare two numbers. When placed between the numbers, it will return the boolean value true if they equal, and false otherwise.

int Level { 10 };

// Level is 10, so isLevel10 will be true
bool isLevel10 { Level == 10 };

// This will be false
bool isLevel15 { Level == 15 };

We can also compare two integer variables:

int Level { 20 };
int TargetLevel { 20 };

// This will be true
bool isTargetLevel { Level == TargetLevel};

We also have the != operator, which will do the exact opposite. It will evaluate to true if the two numbers are not equal, otherwise it will return false.

int Level { 10 };
bool isNotLevel10 { Level != 10 }; // false
bool isNotLevel15 { Level != 15 }; // true

We have 4 other useful operators we can use with numbers:

  • The greater than operator: >
  • The greater than or equal to operator: >=
  • The less than operator: <
  • The less than or equal to operator: <=

Let's look at some examples:

int Level { 10 };

bool isAboveLevel10 { Level > 10 }; // False
bool isAtLeastLevel10 { Level >= 10 }; // True

bool isBelowLevel10 { Level < 10 }; // False
bool isLevel10OrBelow { Level <= 10 }; // True

Floating point numbers have these operators too, and we can compare float and int values freely.

float Health { 100.0 };

// True
bool isHealthy { Health > 50.0 };

// True
bool isMaxHealth { Health >= 100 };

We can also combine maths with the boolean operators, creating more complex expressions:

float Health { 100.0 };
float MaxHealth { 150.0 };

// True
bool isAbove50Percent { Health / MaxHealth > 0.5 };

Test your Knowledge

Simple Booleans

After running the following code, what will be the value of MyBoolean?

bool MyBoolean { 15 > 15 };

After running the following code, what will be the value of MyBoolean?

bool MyBoolean { 15 >= 10 + 5 };

Inverting Booleans with the ! Operator

We can invert booleans (ie, converting true to false, or false to true) using the ! operator. For example:

bool isAlive { true };
bool isDead { !isAlive }; // false

Combining Booleans

We can combine two or more booleans to evaluate more complex situations. This can be done using two ampersands - the && operator.

It allows us to check if two things - the left and right operands - are both true. && is sometimes referred to as the "logical and" operator:

int Level = 10;
bool isAlive = true;

// This will be true
bool isReady { Level == 10 && isAlive };

We can also use the "logical or" operator denoted by || to evaluate if either the left or right operand is true. For example:

int Level = 10;

// This will be true
bool isReady { Level == 10 || Level == 20 };

We're not restricted to just combining two booleans. We can test as many conditions as we desire by using the operators multiple times in a single expression:

// true only if ALL conditions are true
Condition1 && Condition2 && Condition3;

// true if ANY condition is true
Condition1 || Condition2 || Condition3;

The following example uses multiple lines of code to initialize a single value. We can add additional space to our code as needed to make things clearer:

int Level = 10;
bool isDead { true };

// This will be true because Level == 10 is true
bool isMilestoneLevel {
  Level == 10 || Level == 20 || Level == 30
};

// This will be false because !isDead is false
bool canStartQuest {
  Level >= 10 && Level <= 20 && !isDead
};

We can use both || and && operators in the same statement. Typically, when doing this, we will also need to introduce brackets ( and ) to specify how our checks get grouped.

int Level { 10 };
bool isAlive { true };

// This will be true
bool isLevel10Or20AndAlive {
  (Level == 10 || Level == 20) && isAlive
};

Test your Knowledge

Compound Booleans

If Level is an integer value, when is isCorrectLevel true after running the following code?

bool isCorrectLevel { Level < 10 && Level > 20 };

After running the following code, what is the value of isDead?

int Health = 0;
bool isImmortal = false;
bool isDead { Health == 0 && !isImmortal };

Common Mistakes - Not Repeating the Variable Name

There are a few common mistakes that are made when working with booleans.

The first mistake is believing we don't need to repeat the variable name when combining multiple booleans. Variations of this error typically look something like this:

1int Level { 15 };
2
3// This will be true
4bool isReady { Level == 10 || 20 };

Line 4 makes sense in plain language - "is Level equal to 10 or 20?"

But it's a little too ambiguous for code. It gets interpreted as (Level == 10) || (20)

Because 20 is considered true, the overall boolean simplifies to false || true, which further simplifies to true.

To fix the above mistake, we need to specify the variable we're comparing against each time, as shown below.

int Level { 15 };

// This will now be false
bool isReady { Level == 10 || Level == 20 };

Common Mistakes - Not Controlling the Order of Operations

Another common mistake comes from not using brackets when combining the || or && operator, in a statement like this:

int Level { 10 };
bool isAlive { false };

// This will be true, because Level == 10
bool isReady {
  Level == 10 || Level == 20 && isAlive
};

When booleans combine || and &&, the && operators are evaluated first. As a result, line 6 gets interpreted as the following:

Level == 10 || (Level == 20 && isAlive)

Therefore, if Level == 10 the combined boolean will be true regardless of the value of isAlive. The code below adds ( and ) in the correct places, to clarify our intent.

int Level { 10 };
bool isAlive { false };

// This will be false, because isAlive is false
bool isReady {
  (Level == 10 || Level == 20) && isAlive
};

Common Mistakes - Using & and |

The final mistake worth highlighting is not using the correct operators. The boolean operators we usually want use two characters - && and ||

The problem is that & and | are also valid operators - commonly called bitwise operators - which we cover in detail later.

Bitwise operators are used less frequently than their logical counterparts. However, because they are valid operators, our tools often won't realize we've made a mistake - instead we will just have a bug.

bool A{1 & 2}; // false
bool B{1 && 2}; // true

If our code is compiling and running successfully, but our boolean does not have the value we expect, it's worth double-checking to ensure we're using the correct operators.

Summary

In this lesson, we've covered several key aspects of using booleans. Here's a quick recap of what we've learned:

  • Basics of Booleans: Introduced to booleans as true or false values.
  • Creating Booleans: Learned how to create booleans by comparing numbers using operators like ==, !=, >, <, >=, and <=.
  • Inverting Booleans: Discovered the use of the ! operator to invert boolean values.
  • Combining Booleans: Learned to combine booleans using && (logical AND) and || (logical OR) operators.
  • Boolean Order of Operations: Practiced creating complex boolean expressions and controlling their evaluation order with parentheses.
  • Common Mistakes: Identified and corrected common mistakes like improper use of operators and incorrect grouping of conditions.
Next Lesson
Lesson 6 of 60

Types and Literals

Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Booleans Take a Byte of Memory
If booleans only store true/false, why do they take up a whole byte of memory?
Safe Floating-Point Comparisons
How do I handle floating-point comparisons when the numbers might not be exactly equal?
Optimizing Boolean Logic
How can I optimize boolean expressions when I have many conditions to check?
Tracking Boolean State Changes
How do I handle situations where I need to track the history of boolean state changes?
Not Operator vs Equals False
When should I use ! versus == false when checking if a boolean is false?
Debugging Complex Boolean Logic
How do professional programmers debug complex boolean expressions?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant