bhylu.com

Advertisements

C++ Enums

Use enum class for a delivery state and map each state to a readable label.

How it works

An enum class defines named values in its own scope and avoids ordinary implicit conversion to int. That reduces accidental mixing between unrelated state types. It does not make a cast from arbitrary outside integers a validator; input needs a deliberate mapping. A switch can list the states your application handles. Persistent formats should use stable external codes and version rules rather than writing the enum’s native object representation directly to disk.

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 enums.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 · enums.cpp

#include <iostream>
#include <string_view>

enum class State { planned, loaded, delivered };
std::string_view state_label(State state) {
    switch (state) {
        case State::planned: return "planned";
        case State::loaded: return "loaded";
        case State::delivered: return "delivered";
    }
    return "unknown";
}

int main() {
    State state{State::loaded};
    std::cout << "Status: " << state_label(state) << '\n';
}

Expected result

Status: loaded

The function returns views of static string literals, so their storage outlives every call. The fallback acknowledges that a value outside the named set can exist after explicit conversion or invalid deserialization. Keep state transitions in methods when not every named transition is allowed, such as preventing a delivered parcel from becoming loaded again without a new event.

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.