0Pricing
C++ Academy · Lesson

Early Returns break continue and goto

Refactor nested conditionals with early returns and use break, continue and goto judiciously.

The Pyramid of Doom

Deeply nested conditionals are hard to read. Early returns flatten the structure dramatically.

// Pyramid
int process(int n) {
    if (n >= 0) {
        if (n < 100) {
            if (isValid(n)) {
                return compute(n);
            }
        }
    }
    return -1;
}

Refactor with Early Returns

Bail out as soon as a precondition fails. Each guard clause is a flat one-liner.

int process(int n) {
    if (n < 0)      return -1;
    if (n >= 100)   return -1;
    if (!isValid(n)) return -1;
    return compute(n);
}

All lessons in this course

  1. Branching: if-else, ternary, switch-case
  2. Loop Patterns: for, while, do-while
  3. Range-Based for Loop with Containers
  4. Early Returns break continue and goto
← Back to C++ Academy