Learn C++ · 3/15

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

cpp
#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?

cpp
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:

cpp
if (loggedIn) 
    grantAccess(); 
    logUser(); // 🚨 BUG: This line runs EVERY TIME, regardless of 'loggedIn'.

Good Practice (The "Allman" or "K&R" style):

cpp
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

cpp
#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:

cpp
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 the break.

🧠 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.

cpp
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.

cpp
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 received

Real Life Scenario: A while loop is like looking at the rain before going outside (you might never go out). A do-while loop 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:

  1. Initialization: Runs once (usually sets a counter).
  2. Condition: Checked before every iteration.
  3. Update: Runs at the end of every iteration.
cpp
//   (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:

cpp
#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).

  1. auto: Let the compiler figure out the type.
  2. &: Use a reference (point to original memory, don't copy).
  3. const: Promise not to modify the original data.
cpp
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

  1. Avoid Deep Nesting: If you have an if inside an if inside a while inside a for, your code is "Spaghetti." Refactor it into functions.
  2. Use break and continue sparingly:
    • 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).
  3. Infinite Loops: while(true) { ... } is actually common in Game Development (the Game Loop) and Server listening. Just make sure there is an internal break condition!

📚 References & Further Reading

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 event type and an associated integer value.
  • struct Report: The summary structure your function must populate and return.

Requirements

  1. Implement the logic for the process_events function.
  2. You must use a range-based for loop to iterate through the input vector events. For efficiency, use a constant reference.
  3. Inside the loop, you must use a switch statement to handle the logic based on event.type.
  4. Implement the following processing logic:
    • LOGIN and LOGOUT: These events signify a session change. Increment the session_changes counter. You can use fallthrough for these two cases.
    • POST and COMMENT: These events contribute to user engagement. Add the event's value to the total_engagement_score.
    • ERROR: Check the event value. If it is greater than 500, increment the critical_errors counter. Otherwise, ignore it.
    • SYSTEM_MSG: These events are for internal logging and should be skipped entirely in the report. Use the continue keyword to proceed to the next event immediately.
    • UNKNOWN: For any other event type, increment the unknown_events counter. This should be the default behavior.
  5. Ensure you use break statements correctly to prevent unintended fallthrough between different case groups in your switch statement.

Expected result

Your code should correctly implement the process_events function. A successful solution will feature:

  • A range-based for loop iterating over the events vector, written as for (const auto& event : events).
  • A switch (event.type) statement inside the loop.
  • case EventType::LOGIN: followed by case EventType::LOGOUT:, which increments report.session_changes and then has a break;.
  • case EventType::POST: and case EventType::COMMENT: that add event.value to report.total_engagement_score before a break;.
  • case EventType::ERROR: containing an if (event.value > 500) block to increment report.critical_errors, followed by a break;.
  • case EventType::SYSTEM_MSG: containing only a continue; statement.
  • A default: case that increments report.unknown_events and ends with a break;.
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.