×

C++ Enumeration

C++ Enumeration

In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets where the sets me of various types.

Let us consider a week which has 7 days or all four directions. This kind of set is served very well using Enum in C++.

Enum in C++ is final implicit and constants are static. It can be thought of as classes that have well-defined or fixed sets of constants.

Consider these arguments to learn more about Enum:

  1. It can be traversed.
  • It can have methods, fields, and constructors.
  • It can be easier with switch statements.
  • It enhances type safety.
  • It cannot extend classes. Although, it may implement various interfaces by internally extending the enum class.

Generally, enum is a keyword used for enumeration in C++. It is used specifically with integral constants to enhance code readability and maintainability.

Consider the following syntax of enum:

enum enum_name {constant1, constant2, ……..};

Example:

  enum animals{cow, horse, dog, cat};
  enum card_deck{ace=4, kind=4, spade=4}; 

Let us look at some programming examples to understand better.

Example 1: Generic use

 #include<bits/stdc++.h>
 using namespace std; 
 enum animals { Dog, Cat, Wilderbeast, Cow }; 
 int main() 
 { 
     animals pet; 
     pet = Dog; 
     cout << "Pet: " << pet+1<<endl; 
     return 0; 
 } 

Output:

C++ Enumeration

Explanation:

The above code is the simplest demonstration of working with enum in C++. We have assigned the enum keyword before the enum variable's name and have contained it in the various animal's names. The task is to return the position of the animal. To do this, we assigned the enum variable with another variable pet that holds the container's value. The container value with their respective position is then displayed on the console.

Note: There can be an N number of values in the containers. It is better to use lists or arrays in such cases, which allow random access. Although enum provides us the same features, it may increase the space complexity if the container's size is not defined on priority.

Example 2: Using Switch Statement

 #include <bits/stdc++.h>
 using namespace std;
 int main()
 {
     enum Direction { North, South };
     Direction direction = North;
     switch (direction)
    {
     case North:
         cout << "Direction is North";
         break;
     case South:
         cout << "Direction is South";
         break;
     default:
         cout << "Direction can be either North or South";
  }
     return 0;
 } 

Output:

C++ Enumeration

Explanation:

We have used the enum keyword with enumerated key names as directions with two values: North and South in the above code. We have also associated the enumerated keyword with the direction, which is assigned value as North initially. We have defined a switch case that takes direction as an argument and checks if the argument is North or South. If any of these two directions exist in the program, it will be printed, or else the default case will be displayed on the console through the switch statement.

Example 3: Traversing with the enum

 #include <bits/stdc++.h>
 using namespace std;
 enum home_groceris
 {
     Brush,
     Paste,
     Toothskie,
     Watergun,
     Floss,
     Pan,
     Spoon
 };
 int main()
 {
     int x;
     // Traversing the home_groceris enum
     for (x = Brush; x <= Spoon; x++)
         cout << x << " ";
     return 0;
 } 

Output:

C++ Enumeration

Explanation:

The above code is a demonstration of traversing using enum. We have defined an enumerated name as home_groceries and assigned certain items in the containers. In the driver code, we have defined a variable x that will iterate over the container's items from beginning to end. The output is shown in the picture is the respective count or, say, indexes of the items present in the enumerated container.

Advantages and Disadvantages of Enum

  1. Enum works well with string, but sometimes they don't work properly with numbers.
  • Since enumeration is space-concerned, it possesses no capability to work with additional meta-data.
  • While iterating through enumeration containers, enum is sufficient only in case the container is not too large. Random accessing is easy yet time-consuming.
  • Enumerators can implement many interfaces, but it fails in extending classes.
  • The advantage of using enumerators in C++ includes a lower maintenance requirement, improved program readability, and better-debugging capability.
  • Another advantage is that enumerated constants are generated automatically by the compiler. Conversely, symbolic constants must be manually assigned values by the programmer

Related Topics

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Implementing the sets without C++ STL containers

Many practical features and tools in C++ support us in programming competitions. One of these parts is a set from the Standard Template Library (STL), which offers an effective way...

6 minutes read.

C++ Data Abstraction

Object-oriented programming (OOP) provides a number of characteristics that enable programmers to design programmes based on a variety of ideas, reducing errors and increasing program flexibility. The abstraction of data...

7 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Bits stdc++.h in C++

<bits/stdc++.h> in C++ In essence, it is a header file that contains all the standard libraries. It makes sense to use this file in programming competitions to speed up work, especially...

2 minutes read.

SET Data Structure in C++

Generally, in our home, we store food items in a fridge or kitchen efficiently to find them easily and use them. Similarly, in programming, we need to store the data...

6 minutes read.

Dynamic _Cast in C++

C++ is one of the most powerful programming languages. We can write object-oriented and structured programming with the help of C++. In this article, we will learn about the dynamic...

3 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Structs

We frequently encounter scenarios in which we must store a bunch of data, whether of comparable or dissimilar data kinds. Arrays are used to hold a group of data of...

6 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Containership in C++

In C++, it is possible to create an object in one class into another class, and that object is a member of another class. This relationship is known as a...

4 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 minutes read.

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input. Example: // C++ program to convert binary to decimal #include < iostream...

3 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.