true
and false
valuesIn 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.
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:
>
>=
<
<=
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 };
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 };
Booleans are important as they unlock one of the key capabilities of programming - control flow. This allows parts of our code to run only if some boolean condition is true.
The following program uses an if
statement to output some text to the console only if the boolean expression Health <= 0
is true
. The first time we evaluate this expression on line 8, it’s false
, so line 9
is ignored.
When we later evaluate it on line 13, it has become true
, so our logging code is executed:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int Health{100};
6
7 Health -= 50;
8 if (Health <= 0) { // false
9 cout << "I have been defeated";
10 }
11
12 Health -= 50;
13 if (Health <= 0) { // true
14 cout << "I have now been defeated";
15 }
16}
I have now been defeated
We explore if
statements and similar techniques in much more detail in the next chapter.
!
OperatorWe can invert booleans (ie, converting true
to false
, or false
to true
) using the !
operator. For example:
bool isAlive { true };
bool isDead { !isAlive };
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 };
bool isLevel10Or20AndAlive {
(Level == 10 || Level == 20) && isAlive
};
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
};
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 };
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:
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 };
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
};
&
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 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.
In this lesson, we've covered several key aspects of using Booleans. Here's a quick recap of what we've learned:
true
or false
values.==
, !=
, >
, <
, >=
, and <=
.!
operator to invert Boolean values.&&
(logical AND) and ||
(logical OR) operators.true
and false
valuesAn overview of the fundamental true or false data type, how we can create them, and how we can combine them.
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way