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.
These different paths could be based on user input, the state of our objects, randomness, or anything else we might want.
Conditional logic is heavily intertwined with the concept of booleans that we saw earlier. With conditionals, we can tell our functions to execute code only if some boolean expression is true
.
Lets see some examples.
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 of the other techniques we saw in the Boolean
chapter.
How 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 C++ 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 reduced 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 just use it to make our code easier to read. How we space our code is just 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
and Ternary 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 a ternary statement. 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.
How can we initialise a variable called Health
to 0
if isDead
is true, and 100
otherwise?
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 totally 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, lets 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) {
hasHealingSpell ? CastHealingSpell() : RunAway();
} else if (isHostile) {
canSeePlayer ? Attack() : PatrolArea();
}
Our knowledge of conditionals will unlock a lot of additional abilities that we now have access to within our functions.
Over the next few lessons, we will make our functions much more powerful, by introducing the concepts of return values and arguments. See you there!
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way