Learning Hub Search Ctrl K

Legacy C++ › 1. Getting Started

Control Flow

if, switch, for, while, do-while, break, continue and goto.

beginner #if#switch#loops#break#continue#goto

Explanation

  • Selection: if / else if / else, switch, and the conditional operator ?:.
  • Iteration: for, while, do ... while (runs at least once).
  • Jumps: break leaves the nearest loop or switch; continue skips to the next iteration; return leaves the function; goto jumps to a label (rarely justified).

A switch works on integral or enum values. Each case falls through to the next unless you break.

Example

#include <iostream>

enum Color { RED, GREEN, BLUE };

const char* name(Color c) {
    switch (c) {
        case RED:   return "red";
        case GREEN: return "green";
        case BLUE:  return "blue";
    }
    return "unknown";
}

int main() {
    for (int i = 1; i <= 15; ++i) {
        if (i % 15 == 0)      std::cout << "FizzBuzz";
        else if (i % 3 == 0)  std::cout << "Fizz";
        else if (i % 5 == 0)  std::cout << "Buzz";
        else                  std::cout << i;
        std::cout << (i < 15 ? ", " : "\n");
    }

    int n = 0;
    do { ++n; } while (n < 3);          // body runs once even if the test is false
    std::cout << n << " " << name(GREEN) << "\n";

    int total = 0;
    for (int i = 0; i < 10; ++i) {
        if (i % 2) continue;            // skip odd numbers
        total += i;
    }
    std::cout << total << "\n";         // 0+2+4+6+8 = 20
    return 0;
}

Common pitfalls

  • Missing break in a switch causes accidental fall-through. If deliberate, add a comment.
  • Declaring a variable inside a case without braces can jump past its initialization (compile error).
  • In C++98, a variable declared in a for header is scoped to the loop; very old compilers (VC6) leaked it into the enclosing block.
  • Off-by-one errors: prefer i < n over i <= n - 1, especially with unsigned n.
  • break only exits the innermost loop.

Legacy vs modern

C++11 adds range-based for (for (int x : v)), C++17 adds if (init; cond) and [[fallthrough]].

Exercises

1. What does a switch do if no case matches and there is no default?

It does nothing and continues after the switch.

2. Rewrite a while loop as a for loop: int i = 0; while (i < 5) { f(i); ++i; }

for (int i = 0; i < 5; ++i) f(i);