In a previous lesson, we saw how we could group code into reusable blocks called functions, and how we could then call our functions to execute that code as many times as needed.
Our functions did the same thing every time we called them, but that does not have to be the case. We can apply conditional logic to make our functions (and our program in general) take different paths.
Conditional logic is heavily intertwined with the concept of booleans that we saw earlier. With conditionals, we can tell our functions to perform different actions based on the value of boolean expressions.
These techniques are the foundations of making our programs more dynamic, allowing them to change and react to situations such as user input. Let's get started!
if
StatementsAn if
statement is the most basic form of conditional logic. It is a structure that lets us say "if this boolean is true, run a block of code".
The structure of an if
statement looks like this:
int Health { 50 };
bool isDead { true };
if (isDead) Health = 0;
After running the above code, Health
will have a value of 0
.
We can see this has three components:
if
keyword(
and )
that will result in a booleantrue
The content inside the brackets can be anything that results in a boolean. For example, it could be a variable containing a boolean, a maths comparison such as Health < 50
, or any other technique we’re familiar with.
if
StatementsHow can we set the isDead
variable to true
if Health
is less than or equal to 0
?
Here are some more examples:
bool isDead { false };
int Level { 5 };
float Health { 200 };
if (isDead) Health = 0;
if (!isDead) PlayIdleAnimation();
if (Level == 1) StartTutorial();
if (Level >= 10 && !isDead) StartQuest();
If we want multiple statements to be executed based on the value of a boolean, we can introduce braces - {
and }
- to our if
statement:
if (isDead) {
Health = 0;
DropLoot();
PlayDeathAnimation();
AwardExperience();
}
if
Statements in Functionsif
statements will be located within the bodies of our functions. Let's see what that looks like by improving our TakeDamage
function with an if
statement.
This will cause the monster's isDead
boolean to be updated if the damage reduces its Health
to 0
or below:
void TakeDamage() {
Health -= 50;
if (Health <= 0) isDead = true;
}
We can also add a line to our conditional block that ensures this function cannot ever leave our Health
at a negative value:
void TakeDamage() {
Health -= 50;
if (Health <= 0) {
isDead = true;
Health = 0;
};
}
Note the spacing of our code here - we now have multiple levels of indenting from the left. We indent once to indicate we're inside the body of the function, and indent a second level to indicate we're inside the if
statement within our function.
Remember, the spacing does not matter to the compiler - we use it to make our code easier to read. How we space our code is just a personal preference. All of the following are equivalent examples:
if (Health <= 0)
{
isDead = true;
Health = 0;
}
if (Health <= 0) {
isDead = true; Health = 0;
}
if (Health <= 0) { isDead = true; Health = 0; }
else
StatementsWe can combine an if
statement with an else
statement, to create more complicated conditional logic. In the below example, our code will either call the DropLoot
function or the Attack
function. The path it takes depends on the value of the isDead
boolean.
if (isDead) {
DropLoot();
} else {
Attack();
}
Where both blocks of the if
and else
are simple statements, like in the example above, there is a more concise way of creating our conditional.
We can do this using the ternary operator. The code below is equivalent to the previous example:
isDead ? DropLoot() : Attack();
In this structure, we have our boolean expression, followed by a ?
. Then, we place the statement to be executed if the boolean is true
, followed by the statement to be executed if it is false
, with a :
between them.
Aside from requiring fewer keystrokes, they can also be used in ways where if
statements cannot. This allows us to fundamentally change how we write blocks of code, as demonstrated below:
We want the initial value of our Health
variable to depend on the isDead
boolean. We’ve implemented this as follows:
int Health{100};
if (isDead) {
Health = 0;
}
How can we replace this with a ternary?
else if
StatementsThe if
and else
structure only lets us account for two possible states. However, we can accommodate as many as we need by placing any number of else if
statements after our first if
. For example:
if (Health <= 0) {
isDead = true;
DropLoot();
} else if (Health <= 50) {
RunAway();
} else if (Health <= 100) {
Heal();
} else {
Attack();
}
The final statement does not always need to be an else
. It is acceptable to end with an else if
. In the below example, our code will not do anything if Health
is greater than 100
:
if (Health <= 0) {
isDead = true;
DropLoot();
} else if (Health <= 50) {
RunAway();
} else if (Health <= 100) {
Heal();
}
As a final example, let's see something more complex. We can nest conditional statements - including ternaries - within other conditional statements.
if (Health <= 0) {
isDead = true;
if (hasLoot) {
DropLoot();
}
if (shouldAwardExperience) {
AwardExperience();
}
} else if (Health <= 50) {
canHeal ? CastHealingSpell() : RunAway();
} else if (isHostile) {
canSeePlayer ? Attack() : PatrolArea();
}
We’ve seen how a ternary allows us to check a boolean condition and then, depending on whether the condition was true
or false
, execute one of two expressions.
It’s worth noting that either one of those expressions can be another ternary statement. This allows us to effectively nest terneries within terneries.
For example, consider the following block of code:
if (Health <= 0) {
DropLoot();
} else if (Health <= 50) {
RunAway();
} else {
Attack();
}
It could be implemented using ternary statements like this:
Health <= 0
? DropLoot()
: Health <= 50
? RunAway()
: Attack()
This form is fairly contentious - many style guides suggest terneries should never be nested, but we should be aware that it is a possibility.
Great job on completing this lesson on Conditional Logic! Here's a quick recap of what we've covered:
if
, else if
, and else
statements.Up next, we'll delve into Switch Statements in C++. You'll learn:
Use booleans and if statements to make our functions and programs more dynamic, choosing different execution paths.
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way