Enumerate over an enum in C++


Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.

The following is the syntax of enums.

enum enum_name{const1, const2, ....... };

Here, enum_name − Any name given by user. const1, const2 − These are values of type flag.

The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows −

enum colors{red, black};
enum suit{heart, diamond=8, spade=3, club};

Example

#include <iostream>
using namespace std;
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
int main() {
   cout <<"The value of enum color : "<<red<<","<<black;
   cout <<"\nThe default value of enum suit : "<< heart << "," << diamond << "," << spade << "," << club;
   return 0;
}

Output

The value of enum color : 5,6
The default value of enum suit : 0,8,3,4

Enumerate over an Enum. This is easy process, we can create for loop and here we will start from the first type, and end with the end type. Let us see the code.

Example

#include <iostream>
using namespace std;
enum suit{heart, diamond, spade, club};
int main() {
   for(int i = heart; i<=club; i++) {
      cout << "Card Type : " << i << endl;
   }
}

Output

Card Type : 0
Card Type : 1
Card Type : 2
Card Type : 3

Updated on: 30-Jul-2019

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements