C++ Enumerations

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> 
 
using namespace std;
 
enum month { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 
 
int main() 
 
{ 
 
    month m; 
 
    m = Oct; 
 
    cout << “Month: “ << m<<endl; 
 
    return 0; 
 
}  

Output :

Month : 9