How to use enums in C++?

How to use enums 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};

The following is an example of enums.

Example

 Live Demo

#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 <<"&bsol;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

In the above program, two enums are declared as color and suit outside the main() function.

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

In the main() function, the values of enum elements are printed.

cout <<"The value of enum color : "<<red<<","<<black;
cout <<"&bsol;nThe default value of enum suit : "<<heart<<","<<diamond<<","<<spade<<","<<club;

Advertisements