C++ Enumeration (enum)

C++ Enumeration (enum): It is a user-defined data type which can be assigned with some limited values. These values are defined by the programmer at the time of declaring the enumerated type. For defining the enumeration “enum” keyword is used. C++ enums can be thought of as classes that have a fixed set of constants. Enumerator types of values are also known as enumerators.



Syntax: enum enumerated-type-name{value1, value2, value3…..valueN};

C++ Enumeration (enum)

Important Points to Remember

  • improves type safety
  • can be easily used in switch
  • can be traversed
  • can have fields, constructors and methods may implement many interfaces but cannot extend any class because it internally extends Enum class

Example:

#include<bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    // Defining enum Gender 
    enum Gender { Male, 
                  Female }; 
  
    // Creating Gender type variable 
    Gender gender = Male; 
  
    switch (gender) { 
    case Male: 
        cout << "Gender is Male"; 
        break; 
    case Female: 
        cout << "Gender is Female"; 
        break; 
    default: 
        cout << "Value can be Male or Female"; 
    } 
    return 0; 
}

Output:

Gender is Male

Example 2

#include<bits/stdc++.h> 
using namespace std; 
//Defining enum Year 
enum year { Jan, 
            Feb, 
            Mar, 
            Apr, 
            May, 
            Jun, 
            Jul, 
            Aug, 
            Sep, 
            Oct, 
            Nov, 
            Dec }; 
int main() 
{ 
    int i; 
  
    // Traversing the year enum 
    for (i = Jan; i <= Dec; i++) 
        cout << i << " "; 
  
    return 0; 
} 

Output:

0 1 2 3 4 5 6 7 8 9 10 11