C++ - Enumeration (Enum)



In C++, an enumeration (or, enum) is a user-defined data type, where it consists of a set of named integral constants.

Creating (Declaring) Enumeration Type

To create an enumeration (enum), use the enum keyword followed by the name of the enumeration and a list of the named values further enclosed within curly braces.

Syntax

The following is the syntax to create an enumeration −

 enum enumName { Enumerator_value1, Enumerator_value2, Enumerator_value3, // So on }; 

Here,

  • enum is the keyword to declare enumeration type.
  • enumName is the name of the enumeration.
  • Enumerator_Value1, Enumerator_Value1, Enumerator_Value1, and so on are the integral constants.

Accessing Enumeration

You can access enumeration (enum) by declaring it with a variable name inside the int main() body and calling it as per requirement.

Syntax

Here's a syntax for accessing or calling an enum:

 enum enumName { Enumerator_value1, Enumerator_value2, Enumerator_value3, // So on }; // Creating variable and assigning value enumName enam_var = value; 

Here,

  • enumName is the declared variable name of an enum.
  • variableName is the variable name of enumerators (values defined within an enum).

Example of C++ Enumeration

In the following example, we are declaring an enumeration type, declaring an enum's variable/object, and accessing enum constants. Consider the following example −

 #include <iostream> using namespace std; // Define an enumeration called Day, for a days of week enum Day { Sunday, // 0 Monday, // 1 Tuesday, // 2 Wednesday, // 3 Thursday, // 4 Friday = 45, // 45 Saturday // 46 }; int main() { // Declaring a variable for a day Day get1 = Wednesday; cout<<get1<<endl; cout<<Saturday<<endl; return 0; } 

Output

 3 46 

Explanation

In above code, by default explicitly, each day of the week value has been assigned a unique integer value ranging from 0 to 6 to all days of a week, However if we explicitly assign the value 45 to Friday, the enumeration property will cause the sequence to continue from that particular point, therefore the value for remaining Friday and Saturday will become 45 and 46 respectively completing series further on.

Types of C++ Enumeration

There are generally two type of enums in C++ −

1. Unscoped Enums

Unscoped enums are the traditional form of enumeration in C++. They are defined using the enum keyword with enumerator names declared within the enclosing scope. Since the enumerator names are added to the surrounding scope, which can lead to name collisions if not managed carefully, It can be used directly in the code, which is like a set of labels which represent specific numbers.

It automatically assigns integer values starting from zero, unless explicitly assigned, and implicitly convertible to integers.

Example

 #include <iostream> using namespace std; enum RGB { Red, // 0 Green, // 1 Blue // 2 }; void printColor(RGB color) { switch (color) { case Red: cout << "Color is Red"; break; case Green: cout << "Color is Green"; break; case Blue: cout << "Color is Blue"; break; } } int main() { RGB myColor = Red; // Here, no need to specify enum name int value = myColor; // Implicit conversion to int cout << "Integer value: " << value << endl; // Outputs: 0 printColor(myColor); // Outputs: Color is Red return 0; } 

Output

 Integer value: 0 Color is Red 

2. Scoped Enums (enum class)

Scoped enums, introduced in C++11, are defined using the enum class. They provide better type safety and are more organized, where their enumerator names are scoped within the enum. Which means keeping their labels within a specific group, so you need to mention the group name when you use them. This helps avoid confusion if you have similar labels in different groups.

Enumerator names are scoped within the enum type, meaning you must use the enum name to access them. No implicit conversion to integers which helps enhance type safety.

Example

 #include <iostream> using namespace std; enum class Color { Red, // Implicitly 0 Green, // Implicitly 1 Blue // Implicitly 2 }; // Usage int main() { Color myColor = Color::Red; // Must use enum name // int value = myColor; // Error: no implicit conversion // Explicit conversion to int if needed int value = static_cast<int>(myColor); // value = 0 cout << "Integer value: " << value << endl; // Outputs: 0 return 0; } 

Output

 Integer value: 0 

Scoped Vs. Unscoped Enums

FeaturesUnscoped EnumsScoped Enums (enum class)
Scope of EnumeratorsGlobal scopeScoped within the enum type
Name ConflictsPossibleAvoided
Implicit ConversionYesNo
Type SafetyLessMore
Underlying TypeDefault is intCustom type can be specified

Comparing Enum Values

Enum values can be compared just like integer comparison. Consider the following example −

Example

 #include <iostream> using namespace std; enum class Color { Red, Green, Blue }; int main() { Color myColor = Color::Green; if (myColor == Color::Green) { cout << "The color is green!" << endl; } else { cout << "The color is not green." << endl; } return 0; } 

Output

 The color is green! 

Enum as Function Parameters

You can pass enums as parameters to functions. To pass enum as parameter in function, you need to specify the enum name along its instance.

Example

In the following example, we are passing enum as parameter −

 #include <iostream> using namespace std; enum class Color { Red, Green, Blue }; // Function that takes an enum as a parameter void printColor(Color color) { switch (color) { case Color::Red: cout << "Red" << endl; break; case Color::Green: cout << "Green" << endl; break; case Color::Blue: cout << "Blue" << endl; break; } } int main() { Color myColor = Color::Blue; printColor(myColor); return 0; } 

Output

 Blue 

Common Use Cases of Enum

The following are some of the common use cases of enum −

1. State Management

 enum class GameState { MainMenu, Playing, Paused, GameOver }; 

2. Configuration Options

 enum class LogLevel { Info, Warning, Error, Debug }; 

3. Command Types

 enum class Command { Start, Stop, Pause, Resume }; 

4. Direction and Movement

 enum class Direction { Up, Down, Left, Right }; 

Benefits of Using Enums

  • Improved Readability and Maintenance − Enums provide meaningful names for values which makes the code clearer and easier to understand and maintain.
  • Type Safety and Namespace Management − Enums in C++ restrict the assigned values, especially with scoped enums, which reduces errors and avoids name conflicts.
  • Organized Code Structure − Enums helps in enhancing organization by grouping related constants which improve code readability, enforce type safety, create cleaner function interfaces, and facilitate easier refactoring
  • Enhanced Functionality − Enums work smoothly with switch statements and allow explicit control over underlying types with assigned values.

Limitations of Enums

Despite of having benefits, it still have few limitations given below −

  • Type Safety Issues − Unscoped enums can cause name conflicts and allow implicit conversion to integers which will increase the risk of errors.
  • Limited Functionality − Enums have a fixed set of values and lack of member functions which cannot be extended at runtime.
  • Debugging Difficulties − Debuggers may display enum values as integers which makes it harder to interpret their meaning.
Advertisements
close