C++ if / else / switch: Conditionals, Pitfalls, and switch Fall-through

C++ if / else / switch: Conditionals, Pitfalls, and switch Fall-through

이 글의 핵심

Practical guide to if/else chains, switch, break and fall-through, the ternary operator, and mistakes like using = instead of == or comparing floats with ==.

Basic if

int age = 20;

if (age >= 20) {
    std::cout << "adult\n";
}

if / else if / else

int score = 85;

if (score >= 90) {
    std::cout << "A\n";
} else if (score >= 80) {
    std::cout << "B\n";
} else if (score >= 70) {
    std::cout << "C\n";
} else {
    std::cout << "F\n";
}

Comparison operators

== != < > <= >=

Logical operators

&& (AND), || (OR), ! (NOT)

switch

Discrete integral values; each case usually ends with break unless intentional fall-through.

switch vs if-else

  • switch: exact matches on discrete values
  • if-else: ranges and complex predicates

Fall-through

Without break, execution falls through subsequent case labels. Use [[fallthrough]]; (C++17) to document intent.

Ternary operator

cond ? expr1 : expr2

Nested conditionals

Prefer early returns or small helper functions when nesting gets deep.

Common mistakes

Mistake 1: = vs ==

int x = 10;

// ❌ assignment in condition
if (x = 5) { /* ... */ }

// ✅ comparison
if (x == 5) { /* ... */ }

Mistake 2: missing break

Add break or comment intentional fall-through.

Mistake 3: stray semicolon after if

if (age >= 20);  // empty statement—bug
{
    std::cout << "runs unconditionally\n";
}

Practical patterns: menus and grading

Menus often pair switch with loops; grading uses if/else if chains or helper functions like getGrade(score).

Examples

The Korean article includes grade calculator, ATM-style switch, and leap-year/day-count logic—structure and code patterns are the same.

Common issues

Declarations inside case

Wrap in { } to scope locals, or declare before switch.

Floating-point equality

Use fabs(a-b) < epsilon or integer scaling.

Operator precedence

Use parentheses around mixed && and ||.


  • Loops: for/while
  • std::string guide
  • Functions

Practical tips

Debugging

  • Enable warnings; fix -Wparentheses.

Performance

  • Branch prediction matters less than algorithmic complexity—profile hotspots.

Code review

  • Check switch coverage for new enum values.

Practical checklist

Before coding

  • Clear boundaries for grades/thresholds?

While coding

  • All paths return/handle errors?

During review

  • Tests for edge values?

C++, if, switch, else, conditionals