Conditional Logic

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

Free, Unlimited Access
3D art showing a branching path in a forest
Ryan McCombe
Ryan McCombe
Updated

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!

Using 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 other technique we’re familiar with.

Test your Knowledge

Using if Statements

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

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

The Ternary Operator

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:

Test your Knowledge

Ternary Assignment

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?

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

Nested Terneries

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.

Summary

Great job on completing this lesson on Conditional Logic! Here's a quick recap of what we've covered:

  • Explored how to make decisions in code using boolean expressions.
  • Learned the basics of if, else if, and else statements.
  • Practiced using conditional statements to alter the flow of a program.
  • Dived into ternary operators for concise conditional expressions.
  • Explored nested conditional statements for more complex decision-making.

What’s Next?

Up next, we'll delve into Switch Statements in C++. You'll learn:

  • How to simplify complex conditional logic with switch statements.
  • The benefits and use cases of switch statements compared to if-else chains.
  • Practical examples to solidify your understanding.

Was this lesson useful?

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
Ryan McCombe
Ryan McCombe
Updated
Lesson Contents

Conditional Logic

Use booleans and if statements to make our functions and programs more dynamic, choosing different execution paths.

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
Functions, Conditionals and Loops
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:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • 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 © 2024 - All Rights Reserved