Enumerated Types or Enums in C++ – GeeksforGeeks

Enumerated type (enumeration) is a user-defined data type which can be assigned some limited values. These values are defined by the programmer at the time of declaring the enumerated type.

If we assign a float value in a character value, then the compiler generates an error. In the same way if we try to assign any other value to the enumerated data types, the compiler generates an error. Enumerator types of values are also known as enumerators. It is also assigned by zero the same as the array. It can also be used with switch statements.
For example: If a gender variable is created with value male or female. If any other value is assigned other than male or female then it is not appropriate. In this situation, one can declare the enumerated type in which only male and female values are assigned.

Syntax:

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

enum keyword is used to declare enumerated types after that enumerated type name was written then under curly brackets possible values are defined. After defining Enumerated type variables are created. It can be created in two types:-

  1. It can be declared during declaring enumerated types, just add the name of the variable before the semicolon. or,
  2. Beside this, we can create enumerated type variables as same as the normal variables.
     

enumerated-type-name variable-name = value;

By default, the starting code value of the first element of enum is 0 (as in the case of array) . But it can be changed explicitly.

For example: enum enumerated-type-name{value1=1, value2, value3};

And, The consecutive values of the enum will have the next set of code value(s).

For example:

//first_enum is the enumerated-type-name
enum first_enum{value1=1, value2=10, value3};

In this case, 
first_enum e;
e=value3;
cout<<e;

Output:
11

Example 1: 

Tóm Tắt

CPP




#include <bits/stdc++.h>

using namespace std;

 

int main()

{

    

    enum Gender { Male, Female };

 

    

    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: 

CPP




#include <bits/stdc++.h>

using namespace std;

 

enum year {

    Jan,

    Feb,

    Mar,

    Apr,

    May,

    Jun,

    Jul,

    Aug,

    Sep,

    Oct,

    Nov,

    Dec

};

 

int main()

{

    int i;

 

    

    for (i = Jan; i <= Dec; i++)

        cout << i << " ";

 

    return 0;

}



Output: 

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

 

My Personal Notes

arrow_drop_up