bhylu.com

Advertisements

C++ Switch

Use switch for a small command vocabulary and make every exit from a case deliberate.

How it works

switch selects a matching integral or enumeration case label. It fits discrete commands better than arbitrary ranges of values. Once a case is entered, execution can continue into following cases unless it leaves through break, return or another control transfer. A default provides a policy for an unknown command. Modern C++ can mark intentional fall-through with an attribute, but a beginner command dispatcher is usually clearer when separate actions have explicit exits.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror switch.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · switch.cpp

#include <iostream>

int main() {
    char command{'l'};
    switch (command) {
        case 'l': std::cout << "List rounds\n"; break;
        case 'q': std::cout << "Finish planning\n"; break;
        default: std::cout << "Unknown command\n"; break;
    }
}

Expected result

List rounds

The character selects the list action and break exits the switch. This dispatcher does not read input yet; the stream unit will show how to validate outside text before interpreting it. An enum class is often a clearer internal command type than raw numeric codes. The parser and dispatcher should have distinct responsibilities.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.