Enum types

Enum types are used to indicate an attribute that can acquire a constant set of values, for example, enum Day {Sat, Sun, Mon, Tues, Wed, Thurs, Fri}.

By default, the value of the first enumerator in the declaration starts from 0. It then increments the value of the subsequent enumerators by 1. For the preceding example, the following would be the value of the enumerators:

  • Sat – 0
  • Sun – 1
  • Mon – 2
  • Tues – 3
  • Wed – 4
  • Thurs – 5
  • Fri - 6

We can also override the default values of the enumerators by explicitly defining the values in the declaration itself. For example, in the preceding example, if we do not want the enumerators to start from 0, we can use the following declaration:

enum Day {Sat = 1, Sun, Mon, Tues, Wed, Thurs, Fri}

For the preceding declaration, the enumerators will acquire the following values:

  • Sat – 1
  • Sun – 2
  • Mon – 3
  • Tues – 4
  • Wed – 5
  • Thurs – 6
  • Fri – 7

Each Enumerator attribute also has an underlying data type that, by default, is of type Int. If required, we can also change the type of the enumerated values to long or short. However, it cannot take char as an underlying data type. Refer to the following enum declaration, in which we are setting the type of Enumerator value to short:

enum Day : short {Sat = 1, Sun, Mon, Tues, Wed, Thurs, Fri}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.93.12