C++ Enum Tutorial With Example | Enumeration (or enum) in C++

Like Tweet Pin it Share Share Email
C++ Enum Tutorial With Example | Enumeration (or enum) in C++

C++ Enum Tutorial With Example | Enumeration (or enum) in C++ is today’s topic. Enum (Enumeration) is a user-defined datatype where we specify the set of values for a variable, and the variable can only take one out of a small set of possible values.

C++ Enum Tutorial With Example

An enumeration is the distinct type whose value is restricted to the range of values (see below for details), which may include a several explicitly named constants (“enumerators“). The values of the constants are the values of an integral type known as an underlying type of the enumeration.

Keyword and Syntax

If we want to declare an enumeration, we use the keyword enum. The syntax is following.

enum enum_name {const1, const2, const3,..., const-n};

Example:

enum months {Jan, Feb, March, April, May};

Here, enum name is month and Jan, Feb, March… are the type of months.

See the following program of Enum in C++.

#include<bits/stdc++.h>
using namespace std;
enum months
{
	jan,feb,mar,apr,may,june,july,aug,sep,oct,nov,dec
};
int main()
{
	//here we are checking 
	//which month april is
	months mn;
	mn=apr;
	cout<<"The month number April is: "<<mn;	
	return 0;
}

See the output.

C++ Enum Tutorial With Example

So here, we can see that all the months of a year is declared.

The enum name is months, and in main() the variable for enum is mn. Now, in the month we are assigning the value apr and checking which month the April is.

So, as we know, April is the 4th month. But we can see that the output is 3. So, is it wrong? The answer is NO. Because the number starts at 0 by default. Thus, the answer is 3.

How to change the default value of an enum

Here we are going to assign the different value to an enum. Now, we will take those months only which have 30 days, and will assign the month number to it.

Please see the code below.

#include<bits/stdc++.h>
using namespace std;
enum months
{
	apr=4,june=6,sept=9,nov=11
};
int main()
{
	//here we are checking 
	//which month april is
	months mn;
	mn=nov;
	cout<<"The month number of November is: "<<mn;	
	return 0;
}

See the output.

C++ Enum Tutorial

So, here we have declared the month number to those months which have 30 days.

Why we use enumeration

When we need to choose a specific value from a set of values, then it is better to choose enumeration concept.

For example, suppose we have 7 days in a week, if we use enum we can firstly assign those days in enum set and then we can use those. As a benefit, there will be no chance of taking other values than those 7 days.

Another critical place where they are used frequently is in the switch case statements, where all of the values that case blocks expect can be defined in the enum. By this, there will be a surety that the values which are passing to switch case is not other than our given value.

Program of enum and Switch case

See the following code program.

#include<bits/stdc++.h>
using namespace std;
enum Season{ null, Summer, Rainy, Autumn, Winter, Spring};
int main()
{
	Season season;
	cout<<"What is your favorite seasonn"
        "  1.Summern"
        "  2.Rainyn"
        "  3.Autumnn"
        "  4.Wintern"
        "  5.Springn"
        "> ";
	int ch;
	cin >> ch;
	switch (ch)
  	{
  	case 1: 
	  season=Summer;
	  break;
  	case 2:
	  season=Rainy;
	  break;
  	case 3:
	  season=Autumn;
	  break;
	case 4:
		season=Winter;
		break;
	case 5:
		season=Spring;
		break;
  	default:
	  season=null;
  	}
	if(season==null)
  	cout<<"Hey, that's not a fruit!n";
	else
  	cout<<"That's my favourite too'!n";
}

See the following output.

switch in enum

Scoped enum

On the above, what we have learned is under Unscoped enum. Now, we are going to learn about scoped enum.

As this type of enum is scoped, therefore you don’t have to fear conflicts if you use the same names for enumerator values and can be accessed using scope the resolution operator. Since, there are no implicit conversions from the values of the scoped enumeration to integral types, although the static_cast may be used to obtain the numeric value of the enumerator.

See the following program of scoped enum in C++.

#include <iostream>
using namespace std;
int main()
{
	// "enum class" defines this as a scoped 
	//enumeration instead of a standard enumeration
    enum class Month 
    {
        Jan, // Jan is inside the scope of Month
        Feb,
        March
    };
 
    enum class Week
    {
        Sunday, // Sunday is inside the scope of Week
        Monday,
        Tuesday
    };
 
 	//Jan is not directly accessible any more, we have to use Month::Jan
    Month month=Month::Jan;
	//Monday is not directly accessible any more, we have to use Week::Monday 
    Week week=Week::Monday;
	
	// compile error here, as the compiler doesn't know 
	//how to compare different types Month and Week
    if (month==Jan) 
    	cout << "Month and Week are samen";
    else
        cout << "Month and Week are not samen";
 
    return 0;
}

Now, see the below output.

scoped enum

With standard enumerations, enumerators are placed in the same scope as the enumeration itself, so you can typically access enumerators directly (e.g., JAN).

However, with enum classes, the strong scoping rules mean that all enumerators are considered part of the enumeration, so you have to use a scope qualifier to access the enumerator (e.g., MONTH::JAN). This helps keep name pollution and the potential for name conflicts down.

However, we can compare enum from the same class. See the example here below.

#include <iostream>
using namespace std;
int main()
{
    enum class Month
    {
        Jan,
        Feb,
        Mar
    };
    Month month=Month::Feb;
    if (month == Month::Feb) // this is okay
        cout << "Month is February!n";
    else if (month==Month::Jan)
        cout<<"Month is January!n";
    return 0;
}

See the following output.

scoped in C++

Drawback of Enum

  1. The enumerators have no scope.
  2. The enumerators implicitly convert to implicitly to int.
  3. The enumerators pollute the global namespace.
  4. The type of enumerator is not defined. It just has to be big enough to hold the enumerator.

Finally, C++ Enum Tutorial With Example | Enumeration (or enum) in C++ is over.

Comments (0)

Leave a Reply

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