Enumerations

Enumerations are types that only permit certain values. Under the hood, these "values" are just integers.

Unscoped enumeration

To define an unscoped enumeration, use the enum keyword:

enum Element {
  Fire,
  Water,
  Nature,
  Dark,
  Light,
};

Element monsterElement = Dark;
Element playerElement = Light;

Unscoped enumeration are "less safe" to use than scoped enumeration. They are supported in C++ for historical reasons and interoperability with C.

Use scoped enumeration whenever possible.

Scoped enumeration

Scoped enumeration works like unscoped enumerations, except:

  • you use enum class to define them, and
  • you have to "scope" the values when you mention them
enum class Element {
  Fire,
  Water,
  Nature,
  Dark,
  Light,
};

// You scope them using "Element::"
Element monsterElement = Element::Dark;
Element playerElement = Element::Light;

References

  • C++ Crash Course (Josh Lospinoso)2. Types