C++

C++ Enumeration – Detailed Instructions From A-Z

Enum is a user-defined data type in which we declare a set of values for a variable, and the variable can only accept one of a constrained number of potential values. To define an enumeration, we utilize the enum keyword.

enum direction {East, West, North, South}dir;

The dir at the end of the declaration is an enum variable, and the enumeration name in this case is direction, which can only take one of the four stated values.

To further grasp this, let’s use a clear example:
Here, I gave the enum variable dir the value West, and when I displayed the value of dir, it displayed 1 instead. This is due to the fact that by default, the values are listed in ascending order beginning at 0, with East being at 0, West at 1, North at 2, and South at 3.

imple enum Example

#include<iostream>
using namespace std;
enum direction {East, West, North, South}dir;
int main()
{
   dir = West;
   cout<<dir;
   return 0;
}

Another manner of stating an enum variable

There is another approach to declare an enum variable, as demonstrated in the example above where I specified the enum variable dir during enum declaration.

#include <iostream>
using namespace std;
enum direction {East, West, North, South};
int main(){
   direction dir;
   dir = South; 
   cout<<dir;   
   return 0;
}

Output:

3

In C++, why use enum?

Now that we know what an enum is and how to utilize them in a program, let’s talk about their purpose:
Enums are only used when we anticipate that the variable will take one of the available values, like in the case of the dir variable, which stores the direction. Since there are four possible orientations, this variable can accept any one of the four values; attempting to assign a different random value will result in a compilation error. This improves compile-time checking and helps prevent problems brought on by the use of erroneous constants.

They are also widely used in switch case statements, where all of the values that case blocks anticipate can be specified in an enum. By doing this, we can make sure that the enum variable we provide between switch parenthesis isn’t accepting any value at random that it shouldn’t.

How to alter Enum’s default values

#include <iostream>
using namespace std;
enum direction {East=11, West=22, North=33, South=44};
int main(){
   direction dir;
   dir = South;
   cout<<dir; 
   return 0;
}

Output:

44

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button