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.
enum enumeration_name {enumerator1, enumerator2, ... };
//or
enum {enumerator1, enumerator2...};
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
#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;}