C++ ยท Chapter 23 of 49

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.

Example 1 (cpp)
enum class Color { RED, GREEN, BLUE };
Color c = Color::GREEN;
std::cout << static_cast<int>(c);
Output
1

enum 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.
๐Ÿ’ก Note: Prefer enum class over plain enum in new code to avoid namespace pollution and accidental comparisons.

๐Ÿ“ Quick Quiz

1. What is the default value of the first enum member?

2. Which is safer against naming collisions?

3. How do you access GREEN from an enum class Color?