Chapter 06

Controlling Program Flow

if/else, loops, switch/case, ternary operator, goto, and loop control with break and continue.

In this chapter

  1. if / else
  2. while Loop
  3. do...while Loop
  4. for Loop
  5. Range-Based for Loop
  6. Modifying Loop Behavior
  7. switch / case
  8. Ternary Operator
  9. goto
1

if / else

if (condition) {
    // runs when condition is true
} else if (otherCondition) {
    // runs when otherCondition is true
} else {
    // runs when none of the above are true
}
Always use braces { } even for single-line bodies. Omitting them is a common source of bugs when adding lines later.

2

while Loop

Evaluates the condition before each iteration. If the condition is false from the start, the body never runs.

int i = 0;
while (i < 10) {
    // ...
    ++i;
}

3

do...while Loop

The key difference from a regular while: the condition is evaluated after the body, so the body is guaranteed to run at least once.

do {
    // ...
} while (expression);
The condition is checked at the end of each loop, not the start. Useful for menus or input validation where you always need at least one pass.

4

for Loop

The classic for loop has three optional sections: init, condition, and end expression.

for (int i = 0; i < count; ++i) {
    // ...
}

All Three Sections Are Optional

Any or all of the three sections can be omitted. An empty for loop runs forever:

for (;;) {  // infinite loop — equivalent to while(true)
    // ...
}

Multiple Variables in Init

You can declare multiple variables in the init section, but they must be the same type:

for (int i = 0, j = 10; i < j; ++i, --j) {
    // i goes up, j goes down
}

Multiple Expressions in Condition / End

The exit condition and end expression can reference variables from outside the loop, and the end expression can use the comma operator to update multiple variables:

int extra = 5;
for (int i = 0; i < count && extra > 0; ++i, --extra) {
    // ...
}

5

Range-Based for Loop (C++11)

Iterates over every element in a range (array, vector, string, etc.) without needing an index:

int nums[] = {1, 2, 3, 4, 5};

for (int n : nums) {
    std::cout << n << "\n";
}
Use const auto& as the loop variable type to avoid copying elements and to make intent clear when you don't need to modify them: for (const auto& item : collection).

6

Modifying Loop Behavior

continue

Skips the rest of the current iteration and jumps back to the top of the loop to re-evaluate the condition.

for (int i = 0; i < 10; ++i) {
    if (i % 2 == 0) continue;  // skip even numbers
    std::cout << i;              // prints 1 3 5 7 9
}

break

Immediately exits the entire loop block. Execution resumes at the statement after the closing brace.

for (int i = 0; i < 100; ++i) {
    if (i == 5) break;  // exits when i reaches 5
    std::cout << i;
}

7

switch / case

Checks the result of an expression against a set of constant values. More readable than a long chain of if/else if when matching a single variable to many possible values.

switch (expression) {
    case CONSTANT_A:
        // ...
        break;
    case CONSTANT_B:
        // ...
        break;
    default:            // optional — runs if no case matched
        // ...
        break;
}

Fallthrough

Without a break, execution falls through into the next case and continues evaluating — it does not stop until it hits a break or the end of the switch. This is usually a bug, but can be intentional.

Only compile-time constants are valid in case labels — no variables, no ranges, no expressions. switch also only works with integer types and enums.
// Intentional fallthrough example — C++17 [[fallthrough]] suppresses the warning
switch (grade) {
    case 'A':
    case 'B':
        std::cout << "Pass";  // both A and B reach this
        [[fallthrough]];
    case 'C':
        std::cout << "Marginal";
        break;
}

8

Ternary Operator

A compact inline if/else that produces a value. Syntax: condition ? if_true : if_false

int max = (a > b) ? a : b;
// equivalent to:
// if (a > b) max = a;
// else       max = b;
Best used for simple, single-expression choices. Avoid nesting ternary operators — it becomes unreadable quickly.

9

goto

goto instructs the program to jump to a labeled point in the code.

Start:
    // ...
    goto Start;  // jumps back to the label
Not recommended. goto leads to "spaghetti code" — unstructured jumps that make program flow impossible to reason about. Any use of goto can be replaced with structured loops and functions. Compilers and code reviews will flag it.
← Chapter 5 ↑ Index Chapter 7 →