[2026] C++ if / else / switch: Conditionals, Pitfalls, and switch Fall-through
이 글의 핵심
Complete guide to C++ conditionals: comparison and logical operators, switch vs if-else, fall-through, [[fallthrough]], floating-point compares, and common bugs (= vs ==).
Basic if
아래 코드는 cpp를 사용한 구현 예제입니다. 조건문으로 분기 처리를 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
int age = 20;
if (age >= 20) {
std::cout << "adult\n";
}
if / else if / else
아래 코드는 cpp를 사용한 구현 예제입니다. 조건문으로 분기 처리를 수행합니다. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
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 ==
아래 코드는 cpp를 사용한 구현 예제입니다. 조건문으로 분기 처리를 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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
다음은 간단한 cpp 코드 예제입니다. 조건문으로 분기 처리를 수행합니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
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 ||.
Related posts (internal links)
Practical tips
Debugging
- Enable warnings; fix
-Wparentheses.
Performance
- Branch prediction matters less than algorithmic complexity—profile hotspots.
Code review
- Check
switchcoverage 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?