
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Basic Input/Output
- C++ Modifier Types
- C++ Storage Classes
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Return Values
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Pointers
- C++ Pointers
- C++ Dereferencing
- C++ Modify Pointers
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
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
Features | Unscoped Enums | Scoped Enums (enum class) |
---|---|---|
Scope of Enumerators | Global scope | Scoped within the enum type |
Name Conflicts | Possible | Avoided |
Implicit Conversion | Yes | No |
Type Safety | Less | More |
Underlying Type | Default is int | Custom 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.