What is an enumeration (enum) in C++?
Short answer
An enum defines a type with a set of named integer constants (enumerators), improving readability over magic numbers.
Advertisement
AModel answer
An enum defines a type with a set of named integer constants (enumerators), improving readability over magic numbers. Unscoped enums (enum Color { Red, Green };) put the names in the enclosing scope and implicitly convert to int; scoped enums (enum class) are safer and preferred in modern C++.
enum Color { Red, Green, Blue };
Color c = Green;Real-world example
Named enumerators replace magic numbers for states, making the code self-documenting.
Likely follow-ups
- What is the default underlying type? | Do enumerators convert to int?
Related topics