C++
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C++
-
Section 4: Memory Management
-
Section 5: Templates and Generic Programming
-
Section 6: The Standard Template Library
-
Section 7: Modern C++ Features
-
Section 8: Error Handling
-
Section 9: Multithreading
-
Section 10: Operator Overloading and Type Conversion
-
Section 11: Advanced Topics
-
Section 12: Tooling and Build Systems
-
Section 13: Design Patterns in C++
-
Section 14: Interfacing with C and Systems Programming
-
Section 15: Networking and IPC Basics
-
Section 16: Graphics and Game Programming Basics
-
Section 17: The Boost Libraries
-
Section 18: Data Structures and Algorithms in C++
-
Section 19: Practical Projects
-
Section 20: More Concurrency Patterns
-
Section 21: More OOP and Design Practice
-
Section 22: File I/O and Streams
-
Section 23: More Standard Library
-
Section 24: Practice Exercises
-
Section 25: Interview and Algorithm Practice
-
Section 26: Compiler and Language Internals
-
Section 27: GUI and Application Frameworks Overview
-
Section 28: Testing and Quality Practices
-
Section 29: Numerics Library
-
Section 30: Concepts Library (C++20)
-
Section 31: Ranges Library (C++20) In Depth
-
Section 32: More Utility Library
11: Control Flow: If/Else
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
withdrawalAmountis greater than 0. If it is not, print "Invalid amount." - If the amount is valid, check if the
withdrawalAmountexceeds thedailyLimit. If it does, print "Daily withdrawal limit exceeded." - If it's within the limit, check if the
accountBalanceis sufficient to cover thewithdrawalAmount. 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.
There are no comments for now.