C++ Conditional Branching โ€” if-else Ladders & switch-case Masterclass

โšก Modern C++ (C++17 / C++20 / C++23) ๐ŸŸข Lesson 4 ๐Ÿ“‚ Phase 04: Conditional Statements ๐Ÿ“… 2026 Master Edition
๐Ÿ“Œ Covered in this in-depth guide: if / else if / else ยท Short-Circuit Evaluation ยท Ternary Operator ยท switch-case & break ยท Scoped enum class ยท C++17 if Initializers

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.

1Short-Circuit Logical Evaluation

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!

2Complete C++ Grade Processor Program
C++ โ€” Student Grade Classifier & Enum Switchโ–ถ Run Code in C++ Compiler
#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;
}
3Technical FAQs

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.