← C++ from Scratch Lesson 24 of 62 · 10 XP

Enumerations: enum class

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

enum class is a set of named options:

enum class State { Idle, Run, Jump, Dead };

State s = State::Run;
if (s == State::Dead) { … }
switch (s) {
case State::Idle: …; break;
case State::Run:  …; break;
default: break;
}
int code = static_cast<int>(State::Jump);   // 2 — the options are numbered from 0

Why not just an int? State::Jump reads better than 2, and the compiler won't let you compare a State with a number or with another enumeration. The old enum (without class) doesn't protect you like that and scatters its names into the surrounding scope.

Task. A traffic light: enum class Light { Red, Yellow, Green };. Read the number of steps n. The light starts at Red and on every step changes: Red → Green → Yellow → Red. Print the name of the light after n steps.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.