C/C++ Arena

Step 1 of 7

enum class

An enumeration gives names to a small fixed set of choices: directions, days, game states. C has enum, but its names leak into the surrounding scope and silently turn into int, so the compiler happily compares a Color with a Weekday. C++'s scoped enum, enum class, fixes both problems.

#include <iostream>
#include <string>

enum class Light { Red, Yellow, Green };

std::string name(Light l) {
    switch (l) {
        case Light::Red:    return "red";
        case Light::Yellow: return "yellow";
        case Light::Green:  return "green";
    }
    return "?";   // unreachable for valid values, but keeps every path returning
}

Light next(Light l) {
    switch (l) {
        case Light::Red:    return Light::Green;
        case Light::Green:  return Light::Yellow;
        case Light::Yellow: return Light::Red;
    }
    return Light::Red;
}

int main() {
    Light l = Light::Red;
    for (int i = 0; i < 4; i++) {
        std::cout << name(l) << " ";
        l = next(l);
    }
    std::cout << "\n" << static_cast<int>(Light::Green) << "\n";
}
red green yellow red 
2

How it works

Common mistakes

Your turn: write std::string to_string(Weapon w) covering every value, and int price(Weapon w): rifle 2700, sniper 4750, pistol 300.

Next: std::array