x

C++ Enumerations

PREV    NEXT

What are Enumerations?

  • Enumerations are a user defined data type which consist integral constants. In this, you can specify a set of values for a variable and the variable can select only one out of the set. It has a fixed set of constants.
  • To define enumerations we use ‘enum’ keyword. Enumerations can be used to define days of a week, month, weathers, etc. The enum constants are static and final implicitly.

What are the advantages of using Enumerations?

Some of the advantages of enum are:



  • It can be used in switch case.
  • It improves type safety.
  • It can have fields, constructors and methods.
  • It can implement many interfaces but cannot extend any class.
  • It can be traversed.

Now, let us have a look at the simple example:

  • In the given example, enumeration name is month which can only select one of the twelve values and the ‘m’ is an enum variable. So, in this program we have assigned Oct to the variable.
  • Now, it will print 9 because by default the values start from 0 in an increasing order which means Jan is 0, Feb is 1, Mar is 2 and so on but if, we increment the value of variable ‘m’ than it will print the next value.

Let us have a look at the example:

In this, the output will be 10 as the index value of Oct is 9 but we have incremented the variable ‘m’ by 1 so, it will print the next value of Nov.

PREV    NEXT



Like it? Please Spread the word!