Previously, we covered the essentials of data types, variables, and input/output in Modern C++. Now, it’s time to give our programs direction and logic. Control flow structures—such as conditional statements and loops—enable your code to respond dynamically to varying inputs and conditions.
In this post, we’ll explore:
- Conditional statements (if, else if, else, switch)
- Looping constructs (for, while, do-while, and range-based for)
- Basic error handling techniques using assert and exceptions
Understanding these fundamentals will allow you to write more flexible and robust programs.
Conditional Statements
If/Else Statements
The if statement lets you execute code only when a certain condition is true. An else clause can handle the “otherwise” scenario:
#include <iostream>
int main() {
int x = 10;
if (x > 5) {
std::cout << "x is greater than 5\n";
} else {
std::cout << "x is not greater than 5\n";
}
return 0;
}
For more examples, check out C++ if/else tutorials on YouTube.
Switch Statements
A switch statement is useful when you have multiple possible values for a single variable:
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1: std::cout << "Option 1 selected\n"; break;
case 2: std::cout << "Option 2 selected\n"; break;
default: std::cout << "Invalid option\n"; break;
}
return 0;
}
The switch statement compares choice to each case. If a match is found, the corresponding code executes until a break is encountered. Learn more from the cppreference article on switch statements.
Loops
Loops let you repeat blocks of code. This is especially handy for iterating over arrays, processing user input until a condition is met, or performing repetitive calculations.
For Loops
A for loop is perfect for executing a known number of iterations:
for (int i = 0; i < 5; ++i) {
std::cout << "Iteration: " << i << "\n";
}
While and Do-While Loops
Use while loops when the number of iterations isn’t fixed:
int count = 0;
while (count < 3) {
std::cout << "Count: " << count << "\n";
count++;
}
// do-while executes at least once
do {
std::cout << "This runs at least once!\n";
} while (false);
Range-Based For Loops (C++11 and later)
When iterating over collections like arrays or std::vector, range-based for loops simplify your code:
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << "\n";
}
return 0;
}
Range-based loops automatically handle indexing, making code cleaner and less error-prone. Watch a YouTube tutorial on range-based for loops for more details.
Basic Error Handling
While Modern C++ offers exceptions for robust error handling, let’s start simply:
Assertions (assert): They’re used during development to verify assumptions. If an assumption fails, the program ends with an error message.
#include <cassert>
int main() {
int value = 10;
assert(value > 0); // If false, the program terminates
return 0;
}
Exceptions: Exceptions provide a structured way to handle errors.
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Something went wrong");
} catch (const std::exception& e) {
std::cout << "Error: " << e.what() << "\n";
}
return 0;
}
For a deep dive into exception handling, check out CppCon talks on exceptions or read cppreference’s guide on exceptions.
Next Steps
Now that you’ve learned how to control program flow, you can start writing more interactive and complex applications. In the next post, we’ll delve into functions and parameter passing. We’ll discuss how to break down your code into smaller, reusable pieces and handle data flow between functions effectively.