Conditional Logic in C++

Use booleans and if statements to make our functions and programs more dynamic, choosing different execution paths
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

3D art showing a branching path in a forest
Ryan McCombe
Ryan McCombe
Edited

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.

C++ if Statements

An 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:

  • the if keyword
  • an expression inside ( and ) that will result in a boolean
  • a statement that will be executed if the boolean is true

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.

Test your Knowledge

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

Using if Statements in C++ Functions

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

Using else and Ternary Statements

We 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.

Test your Knowledge

How can we initialise a variable called Health to 0 if isDead is true, and 100 otherwise?

Multiple Conditions using else if Statements

The 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!

Was this lesson useful?

Ryan McCombe
Ryan McCombe
Edited
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

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:

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

Switch Statements

Learn an alternative way to write conditionals, which is often used when we want to take different paths based on a specific value
3D art showing a plumber repairing leaky pipes
Contact|Privacy Policy|Terms of Use
Copyright © 2023 - All Rights Reserved