C++ Enums
An `enum` defines a set of named integer constants, making code more readable than using raw numbers. `enum class` (C++11) is preferred over plain `enum` because it avoids naming collisions and implicit conversions.
By default, enum values start at 0 and increase by 1, but you can assign custom values explicitly.
Plain enum
`enum Color { RED, GREEN, BLUE };` creates constants RED=0, GREEN=1, BLUE=2, but they leak into the surrounding scope.
enum class
`enum class Color { RED, GREEN, BLUE };` requires using `Color::RED` and prevents accidental mixing with plain integers, making code safer.
enum class Color { RED, GREEN, BLUE };
Color c = Color::GREEN;
std::cout << static_cast<int>(c);1enum class values need static_cast<int> to print as a number.
Key points
- enum defines named integer constants.
- enum class (C++11) is scoped and type-safe.
- Values default to 0, 1, 2... unless assigned.
- Use static_cast<int> to print an enum class value.
