Skip to content

Name States with enum class

The Course
•
35 min study

A task is either still to do or done. A first attempt often stores that as flags, bool todo; bool done;, or as a number where 0 means todo and 1 means done. Both cause trouble. Two flags have four combinations, and two of them (both true, both false) mean nothing, so every function has to wonder what to do with them. A plain number accepts 2, 7 and -1, and the reader has to remember which number means what.

An enumeration gives each alternative a name and makes a variable hold exactly one of them. enum class State { todo, done }; defines a new type with two named values, written State::todo and State::done. A State variable cannot be both, and code that reads state == State::done explains itself. The class in enum class makes it a scoped enumeration: the names live inside State, and the values do not quietly turn into integers.

Predict and run

label turns a state into display text. What does this print? What changes if you set state to State::done?

Predict before running C++
#include <iostream>

enum class State { todo, done };

const char *label(State state) {
    switch (state) {
    case State::todo: return "Todo";
    case State::done: return "Done";
    }
    return "Invalid";
}

int main() {
    State state = State::todo;
    std::cout << label(state) << "\n";
    return 0;
}
Check your prediction
Text
Todo

The switch jumps to the matching case and returns its text; with State::done it prints "Done". The line after the switch looks unreachable, but it is not, as the next sections show.

No silent conversions

An old-style enum converts to int automatically, so int n = todo + 3; compiles and means nothing. A scoped enum refuses:

Shell
main.cpp:12:9: error: cannot initialize a variable of type 'int' with an rvalue of type 'State'
   12 |     int n = State::done;
      |         ^   ~~~~~~~~~~~

When you really need the number, for example to write a compact file format, ask for it explicitly with static_cast<int>(State::done), which gives 1. The tracker never does this: its text format writes the words todo and done, so the file stays readable and does not depend on the order the enumerators were declared in.

Let the compiler find the missing case

Leave out default: in a switch over an enum, and list every enumerator. Then, if someone later adds blocked to State, every switch that does not handle it gets a warning. Clang turns this one on by default, so the browser editor shows it too, but there it is only a warning and the program still runs. A build with -Werror, like the course's checker and Day 7's local build, turns it into an error:

Shell
main.cpp:4:13: error: enumeration value 'blocked' not handled in switch [-Werror,-Wswitch]
    4 |     switch (state) {
      |             ^~~~~

A default: branch would silence that warning and quietly treat blocked as "Invalid" everywhere. Exhaustive case lists turn "I forgot to update the report" into a build failure, which is the cheapest kind of bug to fix.

Why the return after the switch matters

A scoped enum has a fixed underlying type, int by default, and any int value converted to it with static_cast is a valid State object, even one with no name. A value like that can arrive from a bad cast or a corrupted file:

A State with no name C++
#include <iostream>

enum class State { todo, done };

const char* label(State state) {
    switch (state) {
    case State::todo: return "Todo";
    case State::done: return "Done";
    }
    return "Invalid";
}

int main() {
    const State odd = static_cast<State>(7);
    std::cout << label(State::done) << "\n";
    std::cout << label(odd) << "\n";
    std::cout << static_cast<int>(State::done) << "\n";
    return 0;
}
Text
Done
Invalid
1

Without the final return, label(odd) would run off the end of a function that must return a value, which is undefined behavior; the compiler also warns about it (-Wreturn-type). The project's valid_fields checks state != State::todo && state != State::done for the same reason: data arriving at a boundary is checked, even when its type looks safe. Casting a number to State yourself is the mistake to avoid; the check is the safety net.

Practice

Exercise

Your turn

Write std::optional<State> parse_state(const std::string& text) that accepts exactly "todo" or "done" and const char* state_name(State) that turns a state back into that text. Run each input through both and print the round trip:

Text
todo -> todo
done -> done
Done -> rejected
later -> rejected
 -> rejected
State checks passed

The fifth input is the empty string. Assert that every accepted state converts back to the same text.

Your workspace C++
#include <cassert>
#include <iostream>
#include <optional>
#include <string>

enum class State { todo, done };

// Write parse_state and state_name here.

int main() {
    // Try "todo", "done", "Done", "later" and "".
    return 0;
}
Hint 1: the idea

Text is the outside world's format and State is the program's. Parsing can fail, so it returns an optional; naming cannot fail for a valid state, so it returns text directly.

Hint 2: a first step

Compare the whole string: if (text == "todo") { return State::todo; }. Do not test only the first character, or "tomorrow" would parse as todo. Write state_name as a switch with both cases and a final return "invalid";.

Show one solution
Run the solution C++
#include <cassert>
#include <iostream>
#include <optional>
#include <string>

enum class State { todo, done };

std::optional<State> parse_state(const std::string& text) {
    if (text == "todo") { return State::todo; }
    if (text == "done") { return State::done; }
    return std::nullopt;
}

const char* state_name(State state) {
    switch (state) {
    case State::todo: return "todo";
    case State::done: return "done";
    }
    return "invalid";
}

int main() {
    for (const std::string text : {"todo", "done", "Done", "later", ""}) {
        auto state = parse_state(text);
        if (state) {
            assert(text == state_name(*state));
            std::cout << text << " -> " << state_name(*state) << "\n";
        } else {
            std::cout << text << " -> rejected\n";
        }
    }
    std::cout << "State checks passed\n";
    return 0;
}
Text
todo -> todo
done -> done
Done -> rejected
later -> rejected
 -> rejected
State checks passed

The comparison is exact, so capitalized "Done" is rejected; a format that accepts several spellings is harder to export back canonically. The assertion is a small round-trip test: text to state and back must give the original text. Day 6 applies the same idea to whole task records. The checkpoint next combines a map, IDs and validation in one update operation.

Was this article helpful?

Your response is saved on this device.