Enumerations in C++

An enumeration is a user-defined type that consists of a set of named integral constants that are known as enumerators.

There are scoped enum and non-scoped enum.

Scoped Enum: enum class Suit {Diamonds, Hearts, Clubs, Spades };

Non-Scoped Enum: enum Suit {Diamonds, Hearts, Clubs, Spades };

Every name in an enumeration is assigned an integral value. By default, the first value is assigned 0, the next one is assigned 1, but you can explicitly set the value of an enumerator.

The benefits of using enumerations include:

  1. Makes code easier to read, which means it is less likely that errors will creep into it.
  2. Make it easy to change values in the future.
Advertisements