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.
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, Unlimited Access
3D art of a wizard character
Ryan McCombe
Ryan McCombe
Edited

In this lesson, we dive into the world 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 };
bool isHealthy { Health > 50.0 };
bool isMaxHealth { Health >= 100 };

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

float MaxHealth { 150.0 };
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 };

Combining Booleans

We can combine two or more booleans to evaluate more complex situations. If we use 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 };

bool isLevel10Or20AndAlive {
  (Level == 10 || Level == 20) && isAlive
};

C++ Doesn't Care About White Space

You may have noticed by now that how you space out your code is not of much importance to the compiler. Spaces, tabs, and line breaks are commonly called white space and you can add or remove them as you wish.

The positioning of syntax like } and ; is what matters from the compiler's perspective. Line breaks and blocks of space are to help us humans make the most sense of the code, so we can generally lay out our code in whatever way we prefer.

Let's see some examples:

// We can have multiple statements on one line
int Level { 10 }; int MaxLevel { 50 };

// We can have one statement across multiple lines
bool isAlive {
true
};

// When we do this, indenting can make things clearer
bool isImmortal {
  false
};

// Spacing a complicated statement across multiple
// lines can make it a bit easier to follow
bool isReady {
  Level == MaxLevel &&
  (isAlive || isImmortal) &&
  Health / MaxHealth > 0.5f
};
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

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

Mistake 1 - Not repeating the variable name in compound 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:

int Level { 15 };

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

Line 3 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.

20 is considered true?

The previous assertion that 20 is true possibly confusing. Programming languages often allow other data types to be treated as booleans. This behavior makes it easier for us to write conditional logic, which we’ll introduce in the next chapter.

A value that will be true when used in a boolean context is often called "truthy", whilst a value that will be converted to false is "falsy" (or "falsey").

In C++ and most other programming languages, the integer value of 0 is falsy, whilst any other integer, such as 20, is truthy.

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 };

Mistake 2 - 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
};

Mistake 3 - Using & and | instead of && and ||

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

The problem is that & and | are also valid operators - commonly called bitwise operators, which we cover in detail later. Bitwise operators are rarely used, but because they are valid, 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.

What's Next?

In our upcoming lesson, we'll delve into an essential tool for every programmer: the debugger. Here's a sneak peek of what you'll learn:

  • Introduction to Debugging: Discover what a debugger is and why it's a critical tool in programming.
  • Using the Debugger in C++: Learn how to use the debugger to step through your C++ code, inspect variables, and understand the flow of your program.
  • Debugging Techniques: Gain insights into various techniques that help identify and fix errors in your code.

Was this lesson useful?

Edit History

  • Refreshed content

  • Fixed syntax error in one of the code examples

  • First Published

Ryan McCombe
Ryan McCombe
Edited
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, Unlimited Access
Types and Variables
3D art showing a progammer setting up a development environment
This lesson is part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 56 Lessons
  • Over 200 Quiz Questions
  • Capstone Project
  • Regularly Updated
  • Help and FAQ
Next Lesson

Introduction to Debugging

Creating a tiny program using numbers and booleans, then adding some breakpoints so we can step through our code in a debugger.
3D art showing a cute ladybird
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved