C++ Conditional Branching โ if-else Ladders & switch-case Masterclass
Welcome to Phase 4 (Chapter 4): C++ Conditional Branching โ if-else Ladders, Logical Operators & switch-case Masterclass! Decision-making structures control execution paths. In this guide, you will master short-circuit evaluation, ternary expressions, scoped enums in switch statements, and grade processing logic.
Logical operators evaluate left-to-right and stop as soon as the outcome is guaranteed:
Short-Circuit Rules:
โข A && B: If A is false, B is NEVER evaluated!
โข A || B: If A is true, B is NEVER evaluated!
#include <iostream>
enum class StudentStatus { Active, Suspended, Graduated };
int main() {
int marks;
std::cout << "Enter student marks (0-100): ";
std::cin >> marks;
if (marks < 0 || marks > 100) {
std::cout << "Invalid marks entered! Must be between 0 and 100.\n";
return 1;
}
if (marks >= 90) {
std::cout << "Grade: A+ (Outstanding)\n";
} else if (marks >= 75) {
std::cout << "Grade: A (Distinction)\n";
} else if (marks >= 60) {
std::cout << "Grade: B (First Class)\n";
} else if (marks >= 40) {
std::cout << "Grade: C (Pass)\n";
} else {
std::cout << "Grade: F (Fail)\n";
}
StudentStatus status = StudentStatus::Active;
switch (status) {
case StudentStatus::Active: std::cout << "Status: Active Student\n"; break;
case StudentStatus::Suspended: std::cout << "Status: Suspended\n"; break;
case StudentStatus::Graduated: std::cout << "Status: Graduated Alumni\n"; break;
}
return 0;
} Q1: What is the assignment inside if condition bug?
Writing if (x = 5) assigns 5 to x (evaluates to true!) instead of comparing if (x == 5). Prevent this with compiler flags `-Wall`.
Q2: Why prefer scoped enum class over un-scoped enum in C++11?
enum class prevents name leaks into enclosing scope and prevents implicit conversion to integer.
Q3: Can switch statements evaluate std::string in C++?
No! C++ `switch` only works on integral types (int, char, enum). For strings, use `if-else` chains or string hashing.
Q4: What is if initializer in C++17?
C++17 allows declaring variables scoped to the if block: if (auto res = calculate(); res > 0) { ... }.
Q5: What is switch fall-through behavior?
If a `case` block omits `break`, execution continues sequentially into the next case. Mark intentional fall-through with `[[fallthrough]];` attribute in C++17.