Learn C++
#include "advanced/enums.hpp"

Enums & enum class in C++

//concept

Enumerations name a fixed set of related constants — days, states, error codes — replacing magic numbers with readable, compiler-checked labels. Plain enum leaks its enumerators into the surrounding scope and converts to int silently (Color::Red colliding with Traffic::Red was the classic pain).

enum class (C++11, scoped enums) fixes both: enumerators stay qualified (Color::Red), no implicit int conversion, and the underlying type is customizable (enum class Flags : uint8_t). New code should use enum class essentially always; plain enum survives for bit-flag arithmetic and C compatibility.

//how it works
1

Name the set

enum class Day { Mon, Tue, Wed }; creates three named constants — self-documenting alternatives to 0, 1, 2.

2

Scoped, no leakage

Day::Mon must always be qualified — two enums can both own a value named On without colliding.

3

No silent int conversion

int x = Day::Mon; fails to compile; static_cast<int>(Day::Mon) converts explicitly when numbering is truly needed.

4

Pick the storage

enum class Code : uint8_t trims storage to one byte — control layout for protocols and packed structs.

//example
#include <iostream>
 
enum class Traffic { Red, Yellow, Green };
 
int main() {
Traffic light = Traffic::Green;
if (light == Traffic::Green) {
std::cout << "go" << std::endl;
}
std::cout << static_cast<int>(Traffic::Red) << std::endl;
return 0;
}
Output
go
0
1light holds the scoped enumerator Traffic::Green — qualified, type-safe, no int in sight.
2The == comparison is between Traffic values, printing go on match.
3static_cast<int> explicitly reveals Red's underlying 0 — conversion only ever on demand.
//use cases
State machines with compiler-checked states instead of stringly-typed modes
Error and status codes that read as names in debuggers and logs
Bit-flag enums with overloaded | and & over enum class (explicit opt-in)
Protocol fields with fixed underlying types matching wire layouts

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.