Trusted answers to developer questions

What are enumerated constants in C++?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Enumeration allows for the creation and usage of a new data type with a defined set of constants that are available as values. The enumerators have a constant integer value ranging from 0 to N, unless specified otherwise. Enums can make the program more readable and easier to manipulate.

Syntax

enum enumeration_name {enumerator1, enumerator2, ... };

//or
enum {enumerator1, enumerator2...};

Explanation

The code below demonstrates two enumerators in practice.

The first enumeration, named languages, contains commonly used programming languages. The compiler then, by default, assigns integer values to each of the languages, starting from 0.

The illustration demonstrates the integer value assigned to each language. my_variable is initialized to swift after declaration. my_variable then prints out the integer value assigned to swift.

Similarly, the second enumeration, named data_structures, contains seven elements. However, the first element has been assigned a value of 5, instead of the default value0. The succeeding elements take values after 5 until some other value is assigned. In this case, the 5th element is assigned a value of 3 and the following elements take up values after that, as shown in the illustration.

Code

#include <iostream>
using namespace std;
int main()
{
enum languages {C, go, python, swift, java};
languages my_variable;
my_variable = swift;
cout<<"my variable: "<<my_variable<<endl;
enum data_structures{array = 5, list, vectors, trees , graphs = 3, stacks, queues};
cout<<array<<'\t'<<list<<'\t'<<vectors<<'\t'<<trees<<'\t'<<graphs<<'\t'<<stacks<<'\t'<<queues<<endl;
return 0;
}

RELATED TAGS

c++
enumeration
Did you find this helpful?