Control Flow: Directing Your Program's Logic
8 min read
Control Flow: Directing Your Program's Logic
Welcome to the decision-making center of C++.
Up until now, your code has been falling like a rock—straight down from the first line of main() to the last. While gravity is great for apples, it's terrible for software. Real software needs to react. It needs to check passwords, retry connections, and process millions of data points without you typing them out one by one.
In this module, we will learn how to make your code "smart" by controlling the order in which statements execute.
1. Making Decisions: if, else if, and else 🚦
The Problem
Imagine a video game where the character dies if their health hits 0. Without decision-making logic, your code would just print "Game Over" immediately after printing "Game Start," regardless of the health value. We need a way to execute code conditionally.
The Solution: The if Statement
The if statement evaluates a condition (a boolean expression). If the condition is true, the code inside the block executes. If it is false, the code is skipped.
Definition: An if statement allows for the conditional execution of a code block based on the truth value of a specified expression.
Syntax and Implementation
#include <iostream>
int main() {
int health = 10;
// The condition is strictly checked inside parentheses ()
if (health < 20) {
std::cout << "⚠️ Warning: Low Health!" << std::endl;
}
// This runs regardless of the if statement
std::cout << "Continuing game logic..." << std::endl;
return 0;
}Expanding Logic: else and else if
What if you want to do one thing if the condition is true, and a completely different thing if it's false?
int score = 75;
if (score >= 90) {
std::cout << "Rank: S (Godlike)" << std::endl;
}
else if (score >= 50) {
// This only checks if the first 'if' failed
std::cout << "Rank: B (Average)" << std::endl;
}
else {
// This runs if NONE of the above were true
std::cout << "Rank: F (Try again)" << std::endl;
}🧠 Under The Hood: Branch Prediction
When a CPU sees an if statement, it often tries to guess the outcome before it actually calculates it to save time. This is called Branch Prediction. If the CPU guesses right, your code flies. If it guesses wrong (e.g., unpredictable random data), it has to flush the pipeline and start over, which costs performance cycles.
Fun Fact: Modern CPUs are like anxious teenagers; they overthink every possible scenario before it actually happens.
🛡️ Industry Standard: Always Use Braces
In C++, valid syntax allows you to omit curly braces {} if the block is only one line.
Don't do this.
Bad Practice:
if (loggedIn)
grantAccess();
logUser(); // 🚨 BUG: This line runs EVERY TIME, regardless of 'loggedIn'.Good Practice (The "Allman" or "K&R" style):
if (loggedIn) {
grantAccess();
}
// Now it's visually obvious where the scope ends.Reference: The infamous Apple "goto fail" SSL bug was caused by a missing brace/indentation error.
2. Choosing Paths: The switch Statement 🔀
The Problem
You are writing a menu system. Usually, this results in the "Stairway to Hell"—a massive chain of else if statements checking the same variable over and over.
The Solution: switch
The switch statement selects one code block to execute from multiple alternatives based on the value of a single integer or enumeration.
Definition: A control statement that allows a variable to be tested for equality against a list of values (cases).
Syntax and Implementation
#include <iostream>
int main() {
int input = 2;
switch (input) {
case 1:
std::cout << "Initializing System..." << std::endl;
break; // Essential! Exits the switch.
case 2:
std::cout << "Loading Settings..." << std::endl;
break;
case 3:
std::cout << "Quitting..." << std::endl;
break;
default:
// Runs if input matches none of the cases
std::cout << "Invalid Selection." << std::endl;
break;
}
return 0;
}⚠️ The Danger Zone: Fallthrough
If you forget the break keyword, C++ will "fall through" to the next case and execute it, regardless of the value.
Intentional Fallthrough:
Sometimes this is useful. If you want cases 1, 2, and 3 to do the same thing:
switch (userLevel) {
case 1:
case 2:
case 3:
std::cout << "Standard Access Granted." << std::endl;
break;
case 4:
std::cout << "Admin Access Granted." << std::endl;
break;
}Modern C++ Tip: If you intend to fall through, use the
[[fallthrough]];attribute (available in C++17) to tell the compiler (and your coworkers) that you did it on purpose and didn't just forget thebreak.
🧠 Under The Hood: Jump Tables
Compilers love switch statements. Instead of comparing x == 1, then x == 2, then x == 3 (Linear time), the compiler often generates a Jump Table. It calculates the memory address of the code to run based on the input value and jumps directly there. This makes switch typically faster than a long else if chain for integers.
3. Looping Concepts: while and do-while Loops 🔄
The Problem
You want to simulate a game engine that keeps running until the user quits, or you need to validate input until the user stops typing gibberish.
The Solution: while Loops
A while loop repeatedly executes a target statement as long as a given condition is true.
The while Loop (Pre-check)
The condition is checked before the loop body runs. If the condition is false initially, the loop body never runs.
int battery = 5;
while (battery > 0) {
std::cout << "Robot is working... Battery: " << battery << "%" << std::endl;
battery--; // Decrement is crucial, otherwise: INFINITE LOOP ♾️
}
std::cout << "System Shutdown." << std::endl;The do-while Loop (Post-check)
The condition is checked after the loop body runs. This guarantees the code executes at least once. This is perfect for interactive menus.
int selection;
do {
std::cout << "Enter 1 to Start, 0 to Exit: ";
std::cin >> selection;
if (selection != 0 && selection != 1) {
std::cout << "Invalid input, try again." << std::endl;
}
} while (selection != 0 && selection != 1);
// Keeps asking until valid input is receivedReal Life Scenario: A
whileloop is like looking at the rain before going outside (you might never go out). Ado-whileloop is going outside first, getting wet, and then realizing you should go back inside.
4. Definite Iteration: for Loops and Range-based for Loops 🔢
The Problem
You need to iterate through an array of high scores, or run a calculation exactly 100 times. Using while loops requires you to manually manage the counter variable, which is prone to errors.
The Solution: The for Loop
A control flow statement for specifying iteration, which allows code to be executed repeatedly.
The Standard for Loop
It consists of three parts:
- Initialization: Runs once (usually sets a counter).
- Condition: Checked before every iteration.
- Update: Runs at the end of every iteration.
// (Init) (Cond) (Update)
for (int i = 0; i < 5; i++) {
std::cout << "Iteration number: " << i << std::endl;
}🌟 Modern C++ Standard: Range-based for Loop
In modern industry C++ (C++11 and later), we rarely use the standard for loop to iterate over collections (arrays, vectors, lists). We use the range-based loop. It's cleaner, safer, and reads like English.
Syntax:
#include <vector>
#include <iostream>
int main() {
std::vector<int> fibonacci = {1, 1, 2, 3, 5, 8};
// Read as: "For every number in fibonacci..."
for (int number : fibonacci) {
std::cout << number << " ";
}
return 0;
}⚡ Optimization Tip: const auto&
When iterating over complex objects (like strings or custom classes), using int number (as above) creates a copy of the data. This is slow.
Industry Standard Pattern:
Use const auto& (constant reference).
auto: Let the compiler figure out the type.&: Use a reference (point to original memory, don't copy).const: Promise not to modify the original data.
std::vector<std::string> inventory = {"Sword", "Shield", "Potion"};
for (const auto& item : inventory) {
// efficient reading of 'item' without copying
std::cout << "Inventory contains: " << item << std::endl;
}5. Control Flow Best Practices Summary
- Avoid Deep Nesting: If you have an
ifinside anifinside awhileinside afor, your code is "Spaghetti." Refactor it into functions. - Use
breakandcontinuesparingly:break: Exits the loop immediately.continue: Skips the rest of the current iteration and jumps to the next one.- Overusing these makes logic hard to follow (spaghetti jumps).
- Infinite Loops:
while(true) { ... }is actually common in Game Development (the Game Loop) and Server listening. Just make sure there is an internalbreakcondition!
📚 References & Further Reading
- C++ Keyword Reference (
if): cppreference.com/w/cpp/keyword/if - The
switchStatement: cppreference.com/w/cpp/language/switch - Range-based for loop: cppreference.com/w/cpp/language/range-for
- Core Guidelines (Stroustrup): isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
Now, go forth and direct the flow of your logic! 🌊
Challenge
Challenge: Implement an Event Processor
You are tasked with creating a function to process a stream of user activity events. Your function will receive a vector of Event structs and must produce a summary Report.
Data Structures (Do Not Modify)
enum class EventType: Represents the type of event.struct Event: Contains the eventtypeand an associated integervalue.struct Report: The summary structure your function must populate and return.
Requirements
- Implement the logic for the
process_eventsfunction. - You must use a range-based
forloop to iterate through the input vectorevents. For efficiency, use a constant reference. - Inside the loop, you must use a
switchstatement to handle the logic based onevent.type. - Implement the following processing logic:
LOGINandLOGOUT: These events signify a session change. Increment thesession_changescounter. You can use fallthrough for these two cases.POSTandCOMMENT: These events contribute to user engagement. Add the event'svalueto thetotal_engagement_score.ERROR: Check the eventvalue. If it is greater than500, increment thecritical_errorscounter. Otherwise, ignore it.SYSTEM_MSG: These events are for internal logging and should be skipped entirely in the report. Use thecontinuekeyword to proceed to the next event immediately.UNKNOWN: For any other event type, increment theunknown_eventscounter. This should be the default behavior.
- Ensure you use
breakstatements correctly to prevent unintended fallthrough between different case groups in yourswitchstatement.
Expected result
Your code should correctly implement the process_events function. A successful solution will feature:
- A range-based
forloop iterating over theeventsvector, written asfor (const auto& event : events). - A
switch (event.type)statement inside the loop. case EventType::LOGIN:followed bycase EventType::LOGOUT:, which incrementsreport.session_changesand then has abreak;.case EventType::POST:andcase EventType::COMMENT:that addevent.valuetoreport.total_engagement_scorebefore abreak;.case EventType::ERROR:containing anif (event.value > 500)block to incrementreport.critical_errors, followed by abreak;.case EventType::SYSTEM_MSG:containing only acontinue;statement.- A
default:case that incrementsreport.unknown_eventsand ends with abreak;.