Skip to Content
Course content

11: Control Flow: If/Else

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request for a junior dev working on a game's inventory system. The player was supposed to be unable to drop "Quest Items"—the critical things you need to finish the game. The dev had written the logic, but they forgot one tiny detail: they didn't handle the case where the inventory was already empty. The result? Every time a player tried to drop an item from an empty bag, the game crashed because it was trying to check the properties of a null object. It was a classic case of assuming the "happy path" and forgetting that code needs to make decisions based on the state of the world.

Making Decisions with If Statements

In C++, we use if statements to tell the program, "Only do this if a specific condition is true." It's the most fundamental way to create a fork in the road for your logic. The condition inside the parentheses must evaluate to a boolean value—either true or false.

Take a look at this snippet. Instead of just printing a message, we're checking a variable first:

int playerHealth = 15;

if (playerHealth <= 0) {
    std::cout << "Game Over!" << std::endl;
} else {
    std::cout << "Keep fighting!" << std::endl;
}

I've used the else block here as a catch-all. If the if condition fails, the else block executes. One thing I always tell my mentees: don't skip the curly braces {}, even for single lines of code. You might see people omit them in some tutorials, but that's a recipe for bugs later when you add a second line to that block and realize it's not actually part of the conditional.

Handling Multiple Possibilities

Rarely is life—or coding—just a binary choice between two options. Usually, you have a handful of different states to manage. That's where else if comes in. It allows you to chain checks together. The program will check the first if; if that's false, it moves to the first else if, and so on. The moment it finds a true condition, it executes that block and skips the rest of the chain.

Let's say we're writing a system to categorize a temperature reading from a sensor:

double temperature = 22.5;

if (temperature > 30.0) {
    std::cout << "Warning: Overheating!" << std::endl;
} else if (temperature < 10.0) {
    std::cout << "Warning: Too cold!" << std::endl;
} else {
    std::cout << "Temperature is within normal range." << std::endl;
}

The order here matters. If you put the most general condition first, the more specific ones will never be reached. Always check for your most restrictive or critical conditions first.

Combining Conditions for Precision

Sometimes a single comparison isn't enough. You might need two or three things to be true at the same time. We handle this using logical operators: && (AND) and || (OR). I find that using these correctly is what separates a "script" from actual robust software.

Imagine you're validating a user's password. It can't be too short, and it can't be empty. You could write two separate if statements, but that's clunky. Instead, combine them:

std::string password = "mySecurePassword123";
int passwordLength = password.length();

if (passwordLength >= 8 && passwordLength <= 32) {
    std::cout << "Password length is valid." << std::endl;
} else {
    std::cout << "Password must be between 8 and 32 characters." << std::endl;
}

In this case, the && operator ensures that both sides are true. If the password is 5 characters long, the first check fails, and the whole expression becomes false immediately. C++ is smart enough to use "short-circuit evaluation," meaning if the first part of an && is false, it won't even bother checking the second part. It saves a tiny bit of processing power, but it's a good habit to keep in mind when the second condition involves a heavy function call.




📋 Practical Task

Exercise: ATM Withdrawal Validator

You are tasked with writing the logic for an ATM withdrawal. Your program should take three variables: double accountBalance, double withdrawalAmount, and double dailyLimit.

Write a program that implements the following logic using if, else if, and else:

  • First, check if the withdrawalAmount is greater than 0. If it is not, print "Invalid amount."
  • If the amount is valid, check if the withdrawalAmount exceeds the dailyLimit. If it does, print "Daily withdrawal limit exceeded."
  • If it's within the limit, check if the accountBalance is sufficient to cover the withdrawalAmount. If not, print "Insufficient funds."
  • If all conditions are met, subtract the amount from the balance and print "Withdrawal successful! Remaining balance: [amount]".

Requirements: Use combined logical operators if you feel they simplify the code, but ensure every error case provides a specific message to the user.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.