Tutorial Study Image

C++ Enumeration


May 28, 2023, Learn eTutorial
344

Enum or enumeration is a data type that is used in C++ programming that consists of named values such as elements, members, etc ..,  that represent integral constants. It offers a method for defining and classifying integral constants. Additionally, it makes the code simpler and easier to maintain. You will discover in-depth information about C++ enums in this tutorial.

We will discover how to use enumeration (enum) in this tutorial. Additionally, with the help of examples, you will discover where enums are frequently used in C++ programming.

C++ Enum: What Is It?

The user-defined data type enum, commonly referred to as enumeration, allows you to establish a new data type with a fixed range of possible values, as well as the variable can choose one value from the set of values. Assume, for example, that you are the proprietor of an ice cream parlor with a small selection of ice cream flavors. Therefore, you only want the clients to choose from that selection of ice creams in your business. This turns into an enumeration with ice cream as the name of the enumeration and various ice cream flavors as its components.

Enumeration

  • Enumerations are a sort of user-defined data that can only have a certain number of values allocated to it.
  • In this, you can provide a variable with a list of possible values, and the variable can only choose one from the list. It has a set of fixed constants.
  • 'enum' is used to define an enumeration.
  • As soon as the enumerated type is declared, the programmer defines these values.
  • Enumerations can be used to define weekdays, months, seasons, and other concepts. Enum constants are static as well as final implicitly.

How to define an enum in C++?

In C++, in order to define an enum, the enum keyword must be used along with the elements that are separated by the commas.

Enum's basic syntax is as follows:


enum enum_name{ element1, element2, element3, element4,};
 

or


enum name_of_enum
{
  Element1,
  Element2,
  Element3,
  Element4,
  Element5,
};
 

Here, the keyword "enum" tells the code what to do, " name_ of_ enum" is the name that will be given to the enum, and "Element 1, Element 2,..., Element 5" are the values that have been assigned to the enumeration.
For example


enum  ice_cream
{
 Vanilla,
Chocolate,
Butterscotch,
Mango,
Pineapple,
Strawberry
}
 

Every one of these components has a value starting at 0, such as vanilla (0), chocolate (1), etc. In C++, the mentioned default values can be changed when the enum is declared.

Example :

enum season { winter, autumn,spring, summer};

The name of the enumeration in this case is a season. Summer, winter, spring, and autumn are all examples of the type of season. Winter starts at 0, spring at 1, and so on by default. During declaration, an enum element's default value can be altered (if it is necessary).


enum season 
{   winter = 0,
spring = 6, 
autumn = 12,
summer = 18,
};
 

Declaration

When declaring an enum variable, include the name of the enumeration as well.


int main()
{
  ice_cream i;
  return 0;
}
 

The enum variable, in this case, is i.

Declaration of Enumerated Types

Only the variable's blueprint is built when an enumerated type is formed. Here's how to generate enum type variables.


enum season { summer ,winter, autumn,spring };
                                                          
int main(){
enum Seasons s;
return 0;
}
 

The enum variable called Season is shown here as s. A season will be represented by this variable.

An enum variable can also be declared as follows:


enum season { summer ,winter, autumn,spring } s;
 

Another example


enum boolean { false, true };

int main(){
enum boolean check;
return 0;
}
 

The variable check of type enum boolean gets created in this case.
Here is an alternative declaration syntax for the same check variable.


enum boolean 
{ 
false, true
} check;
 

Example 1:

A C++ program to identify the direction using enumeration


#include <iostream>
using namespace std;

enum direction { East, West, North, South  };
int main(){
    direction dir;
    dir = North;
    cout << "The Direction: " << dir;
    return 0;
}
 

Output:


The Direction: 2

Example 2:

We employ the static cast operator to output the contents of a void pointer. It changes the pointer's data type from its original void* type to the appropriate data type for the address that the pointer is storing:

Using Enumeration in C++ to Change the Default Value of an Enumsn


#include <iostream>
using namespace std;

enum seasons { spring = 10, summer = 14, autumn = 19, winter = 11};
int main() {
    seasons s;
    s = Autumn;
    cout << "Summer = " << s << endl;
                                                                      
    return 0;
}
 

Output:


Autumn = 19

In C++ programming, why are enums used?

Enum or enumeration is a data type that is used in C++ programming that consists of named values that represent integral constants, such as elements, members, etc. It offers a method for classifying and defining integral constants. Additionally, it makes the code simpler and easier to maintain.

Enums are only used when the variable is expected to have one of the available values.

For example


#include <iostream>
using namespace std;
enum direction { East = 10, West = 20, North = 30, South = 40 } dir;
int main() {
    dir = North;
    cout << "The Size of enum variable " << sizeof(North) << " bytes.";   
    return 0;
}
 

Output:


The Size of enum variable 4 bytes.

Because an integer has a size of 4 bytes. Because of this, using an enum with flags is a smart idea.

The same work can be completed using C++ structures. However, using enums gives you flexibility and efficiency.

How are enums used for flags?

Consider the following example:

enum designFlags { UNDERLINE = 1, ITALICS = 2 BOLD = 4 } button;

Think about creating a button for a Windows program. To work with text, you can set the flags UNDERLINE, ITALICS, and BOLD.
All of the integral constants in the above pseudocode are powers of two for a purpose.

// In binary UNDERLINE = 00000001 ITALICS = 00000010 BOLD = 00000100

Since the integral constants are powers of 2, you can use the bitwise OR | operator to combine two or more flags simultaneously without them overlapping. You can select two or more flags simultaneously by doing this.

For example


#include <iostream>
using namespace std;
enum printFlags { BOLD = 1, ITALICS = 2, UNDERLINE = 4};
int main() {
    int myFlag = UNDERLINE | BOLD ; 

        //    00000001
        //  | 00000100
        //  ___________
        //    00000101
    cout << "Displaying myFlag = " <<  myFlag;

    return 0;
}
 

Output:


Displaying myFlag = 5

You can always see that bold and underlining are utilized when the output is 5.

You can also include the flag in your requirements.

if (myFlag & ITALICS) { // statement for italics }

Italics have been applied to our design in this case. One thing to keep in mind is that the if statement only contains code for italics. Without using enumerations, you can perform practically everything in C++ programming. They can, nevertheless, be quite useful in some circumstances. That is what separates average programmers from exceptional ones.

Advantages of numeration in C++

The following are a few benefits of enum:

  1. The switch case can utilize an enum.
  2. Type safety is increased via an enum.
  3. It is possible to traverse an enum.
  4. Fields, constructors, and methods are all possible for enums.