C++

Chapter 4: Control Flow - Making Decisions with if, else, and switch

By Ali Naqi • October 30, 2025

Chapter 4: Control Flow - Making Decisions with if, else, and switch

C++ Tutorial Series - Chapter 4: Control Flow - The Art of Decision Making with if and switch

Every dynamic program requires the ability to choose. If the user clicks A, do this; if the score is B, reward them; otherwise, do nothing. This branching logic is called Control Flow, and it transforms your linear code into smart, adaptable software. In this chapter, we master the three fundamental conditional tools: if, the if-else if ladder, and the powerful switch statement.

1. The Fundamental Fork in the Road: The if Statement

The if statement is the simplest decision structure. It executes a block of code only if the condition inside its parentheses is evaluated as true. Remember from Chapter 3 that relational and logical operators are designed specifically to produce this true or false value.

The if Structure


if (condition) {
    // This code block runs ONLY if 'condition' is true.
}
// Execution continues here regardless of the outcome.
    

One common shorthand for experienced C++ programmers is omitting the curly braces {} if the if statement controls only a single statement.


int userClicks = 10;
// No braces needed for a single line
if (userClicks > 5) 
    std::cout << "High activity detected." << std::endl; 
    

Warning on Omitted Braces: While compact, omitting braces can lead to sneaky bugs if you later add a second line of code beneath the if. Best practice for beginners: always use curly braces.

The Two-Sided Coin: if...else

The if...else statement is a complete fork in the road. One, and only one, block is guaranteed to execute. If the if condition is true, the else block is skipped. If the if condition is false, the else block runs.


int gameScore = 1200;

if (gameScore > 1000) {
    std::cout << "You passed the level! Proceed." << std::endl;
} else {
    std::cout << "Try again to reach 1000 points." << std::endl;
}
    

2. The Decision Ladder: if...else if...else

When you have a series of mutually exclusive conditions (e.g., A, B, C, D, or Fail), the if...else if...else structure is the most logical choice. It creates a "ladder" where the conditions are checked sequentially from top to bottom.

Key Principle: The First True Condition Wins

As soon as the compiler finds a condition that evaluates to true, it executes that code block, skips the rest of the entire ladder, and continues execution after the final else block. The else at the end serves as the universal "catch-all" if none of the specific conditions above it were met.


// Example: A University Grading System
int studentMarks = 85;

if (studentMarks >= 90) {
    std::cout << "Grade: A - Excellent Work!" << std::endl;
} else if (studentMarks >= 80) {
    // This runs for 80-89. Notice we DON'T need to check for >= 80 AND < 90
    std::cout << "Grade: B - Solid Performance." << std::endl;
} else if (studentMarks >= 70) {
    std::cout << "Grade: C - Passable." << std::endl;
} else {
    // The default case: marks are < 70
    std::cout << "Grade: F - Needs Improvement." << std::endl;
}
    

Nested Conditionals

Sometimes, a condition relies on a previous condition being true. You can place one conditional statement entirely inside another. This is called nesting.


bool isLogged = true;
int subscriptionLevel = 2; // 1=Basic, 2=Premium

if (isLogged) {
    std::cout << "Welcome, User." << std::endl;
    if (subscriptionLevel == 2) {
        std::cout << "Access granted to Premium Content." << std::endl;
    } else {
        std::cout << "Basic content available." << std::endl;
    }
} else {
    std::cout << "Please log in to continue." << std::endl;
}
    
Readability Tip: Nested if statements can quickly become confusing. Use meaningful variable names and indent your code properly to keep the logic clear.

3. The Quick Choice: The Ternary Operator (? :)

The ternary operator is C++'s shortest, most compact conditional operator. It's used to quickly assign a value to a variable based on a simple boolean condition. It's great for one-line decisions.

Syntax: condition ? expression_if_true : expression_if_false;


int userPoints = 55;

// If userPoints >= 50, assign "Winner", otherwise assign "Loser"
std::string status = (userPoints >= 50) ? "Winner" : "Loser";

std::cout << "Game Status: " << status << std::endl; // Output: Winner
    

4. Multi-Way Branching: The switch Statement

When you need to test a variable against many specific constant values (e.g., 1, 2, 3, 4, or 'A', 'B', 'C'), the switch statement is cleaner and often more efficient than a long if...else if chain.

Rules for switch

  • The expression in the switch() parentheses must evaluate to an integral type (int, char, short, long) or an enumeration. You cannot use floats, doubles, or strings!
  • The value after each case must be a constant value (a literal or a const variable).

int menuChoice = 2;

switch (menuChoice) {
    case 1:
        std::cout << "Loading New Game..." << std::endl;
        break; // <-- ESSENTIAL! Exits the switch.
    case 2:
        std::cout << "Opening Settings Menu..." << std::endl;
        break; 
    case 3:
        std::cout << "Exiting Application." << std::endl;
        break;
    default:
        std::cout << "Invalid choice. Please try again." << std::endl;
        break;
}
    

The Critical Fall-Through Trap: The most common bug in switch statements is forgetting the break; statement. Without it, once a case is matched, the code falls through and executes the code for the next case label, and the next, until a break or the end of the switch is reached. This is occasionally intentional (but rare!), but usually disastrous. Always include break; unless you know exactly why you are omitting it.


Chapter 4 Conclusion and Next Steps

Congratulations! You have now mastered the art of control flow. Your program can now adapt, react to user input, and make complex logical choices using if, else if, and switch. This chapter is the bridge between simple sequential code and genuinely interactive software.

In Chapter 5, we tackle repetition. We will introduce Loops (for, while, and do-while), which allow you to automate tasks and run blocks of code hundreds of times with just a few lines. Get ready to automate the boring stuff!