Enumeration in C++
1. Introduction
An enumeration, commonly called an enum, is a user-defined data type in C++ that consists of a set of named constant values.
Enumeration is useful when a variable should have only a limited number of possible values.
Example
Suppose we want to represent days of a week:
enum Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
Instead of using numbers such as 0, 1, 2, etc., we can use meaningful names such as Monday, Tuesday, and Sunday.
2. Definition of Enumeration
Enumeration is a user-defined data type that contains a fixed set of named integral constants.
The keyword used to define an enumeration is:
enum
Example
enum Color { RED, GREEN, BLUE };
Here:
Coloris the enumeration type.RED,GREEN, andBLUEare enumeration constants.
3. Why Use Enumeration?
Enumeration is useful when a variable can have a limited set of predefined values.
For example:
Traffic light
RED YELLOW GREEN
Days
MONDAY TUESDAY WEDNESDAY ...
Gender category
MALE FEMALE OTHER
Direction
NORTH SOUTH EAST WEST
Using meaningful names makes programs easier to read and understand.
4. Syntax of Enumeration
The general syntax is:
enum EnumName { value1, value2, value3 };
Example
enum Color { RED, GREEN, BLUE };
5. Creating an Enumeration Variable
After defining an enum, we can create a variable of that type.
#include <iostream> using namespace std; enum Color { RED, GREEN, BLUE }; int main() { Color c = GREEN; cout << c << endl; return 0; }
Output
1
By default:
RED = 0 GREEN = 1 BLUE = 2
6. Default Values of Enum
If explicit values are not provided, enumeration values normally start from 0 and increase by 1.
Example:
enum Day { Monday, Tuesday, Wednesday, Thursday };
The values are:
| Name | Value |
|---|---|
| Monday | 0 |
| Tuesday | 1 |
| Wednesday | 2 |
| Thursday | 3 |
7. Assigning Custom Values
We can assign our own integer values to enumeration constants.
enum Status { SUCCESS = 1, ERROR = 2, PENDING = 3 };
Now:
SUCCESS = 1 ERROR = 2 PENDING = 3
Example
#include <iostream> using namespace std; enum Status { SUCCESS = 1, ERROR = 2, PENDING = 3 }; int main() { Status s = SUCCESS; cout << s << endl; return 0; }
Output
1
8. Partially Assigning Values
We do not have to assign a value to every enumeration constant.
Example:
enum Number { ONE = 1, TWO, THREE, FOUR = 10, FIVE };
The values become:
| Constant | Value |
|---|---|
ONE | 1 |
TWO | 2 |
THREE | 3 |
FOUR | 10 |
FIVE | 11 |
The next unassigned value normally continues from the previous value.
9. Complete Example of Enum
#include <iostream> using namespace std; enum Color { RED, GREEN, BLUE }; int main() { Color color = BLUE; cout << "Color value: " << color << endl; return 0; }
Output
Color value: 2
10. Enum with switch
Enumeration works very well with the switch statement.
Example
#include <iostream> using namespace std; enum Day { Monday, Tuesday, Wednesday, Thursday, Friday }; int main() { Day today = Wednesday; switch (today) { case Monday: cout << "Today is Monday"; break; case Tuesday: cout << "Today is Tuesday"; break; case Wednesday: cout << "Today is Wednesday"; break; case Thursday: cout << "Today is Thursday"; break; case Friday: cout << "Today is Friday"; break; } return 0; }
Output
Today is Wednesday
11. Enumeration with User Input
We normally cannot directly read an enum value with cin in the same way we read an integer. A common approach is to read an integer and convert it after checking the valid range.
Example
#include <iostream> using namespace std; enum Color { RED, GREEN, BLUE }; int main() { int choice; cout << "Enter color (0=RED, 1=GREEN, 2=BLUE): "; cin >> choice; if (choice >= 0 && choice <= 2) { Color color = static_cast<Color>(choice); cout << "Selected color value: " << color << endl; } else { cout << "Invalid choice"; } return 0; }
Sample Output
Enter color (0=RED, 1=GREEN, 2=BLUE): 1 Selected color value: 1
When converting an integer to an enum, checking that the value is valid is important.
12. Enum and if-else
An enum can also be used with conditional statements.
#include <iostream> using namespace std; enum TrafficLight { RED, YELLOW, GREEN }; int main() { TrafficLight light = RED; if (light == RED) { cout << "Stop"; } else if (light == YELLOW) { cout << "Wait"; } else { cout << "Go"; } return 0; }
Output
Stop
13. Scoped Enumeration (enum class)
C++ provides a safer form of enumeration called scoped enumeration.
It is declared using:
enum class
Example
enum class Color { Red, Green, Blue };
To access its values, we use the scope operator ::.
Color color = Color::Green;
Complete Example
#include <iostream> using namespace std; enum class Color { Red, Green, Blue }; int main() { Color color = Color::Green; if (color == Color::Green) { cout << "Green color selected"; } return 0; }
Output
Green color selected
14. Difference Between enum and enum class
| Feature | enum | enum class |
|---|---|---|
| Scope | Unscoped | Scoped |
| Access | RED | Color::RED |
| Implicit conversion to integer | Allowed in many contexts | Not allowed |
| Name conflicts | More likely | Less likely |
| Type safety | Lower | Higher |
| Recommended for modern C++ | Sometimes | Generally preferred |
Traditional enum
enum Color { RED, GREEN }; Color c = GREEN;
Scoped enum
enum class Color { RED, GREEN }; Color c = Color::GREEN;
15. Name Conflicts in Traditional Enum
Traditional enums can cause name conflicts because their enumerator names can enter the surrounding scope.
For example:
enum Color { RED, GREEN }; enum Traffic { RED, YELLOW };
This can cause a conflict because both enums define RED.
Using enum class avoids this:
enum class Color { RED, GREEN }; enum class Traffic { RED, YELLOW };
Now we can write:
Color::RED Traffic::RED
The names are clearly separated.
16. Converting enum class to Integer
A scoped enum does not automatically convert to an integer.
For example:
enum class Color { Red, Green, Blue };
This is not valid:
int x = Color::Green;
Instead, use static_cast:
int x = static_cast<int>(Color::Green);
Example
#include <iostream> using namespace std; enum class Color { Red, Green, Blue }; int main() { Color c = Color::Blue; int value = static_cast<int>(c); cout << value << endl; return 0; }
Output
2
17. Specifying the Underlying Type
We can specify the integer type used internally by an enum.
Example:
enum class Status : int { Success = 1, Error = 2 };
We can also use types such as:
enum class Status : unsigned char { Success = 1, Error = 2 };
This can be useful when the underlying representation needs to be controlled.
18. Enumeration with Functions
An enum can be passed to a function.
#include <iostream> using namespace std; enum class Level { Low, Medium, High }; void display(Level level) { if (level == Level::Low) { cout << "Low level"; } else if (level == Level::Medium) { cout << "Medium level"; } else { cout << "High level"; } } int main() { display(Level::High); return 0; }
Output
High level
19. Enumeration in a Structure
An enum can be used as a member of a structure.
#include <iostream> #include <string> using namespace std; enum class Gender { Male, Female, Other }; struct Student { string name; Gender gender; }; int main() { Student s; s.name = "Anuradha"; s.gender = Gender::Female; cout << "Name: " << s.name << endl; if (s.gender == Gender::Female) { cout << "Gender: Female" << endl; } return 0; }
Output
Name: Anuradha Gender: Female
20. Array of Enumeration Values
We can create an array containing enum values.
#include <iostream> using namespace std; enum class Day { Monday, Tuesday, Wednesday }; int main() { Day days[3] = { Day::Monday, Day::Tuesday, Day::Wednesday }; for (int i = 0; i < 3; i++) { cout << static_cast<int>(days[i]) << endl; } return 0; }
Output
0 1 2
21. Real-Life Example: Traffic Light
A traffic light has a limited number of states.
#include <iostream> using namespace std; enum class TrafficLight { Red, Yellow, Green }; int main() { TrafficLight light = TrafficLight::Green; switch (light) { case TrafficLight::Red: cout << "Stop"; break; case TrafficLight::Yellow: cout << "Wait"; break; case TrafficLight::Green: cout << "Go"; break; } return 0; }
Output
Go
22. Real-Life Applications of Enumeration
Enumeration can be used in many applications.
1. Traffic System
Red Yellow Green
2. Days of Week
Monday Tuesday Wednesday ...
3. Months
January February March ...
4. User Roles
Admin Teacher Student Guest
5. Order Status
Pending Processing Shipped Delivered Cancelled
6. Directions
North South East West
7. Game States
Start Playing Paused GameOver
23. Enumeration vs Integer
Instead of:
int status = 1;
we can use:
enum class Status { Pending, Approved, Rejected }; Status status = Status::Approved;
The second approach makes the meaning of the value much clearer.
24. Advantages of Enumeration
1. Improves Readability
Meaningful names are easier to understand than numbers.
Instead of:
int status = 2;
we can use:
Status status = Status::Approved;
2. Represents Fixed Choices
Enums are useful when only a predefined set of values is meaningful.
3. Reduces Magic Numbers
Names such as Pending or Approved are easier to understand than unexplained numeric values.
4. Useful with switch
Enums work naturally with switch statements.
5. Provides Type Safety
enum class provides stronger type checking than traditional enums.
6. Makes Code Easier to Maintain
Changing or adding named states is easier than managing unexplained integer values throughout a program.
25. Disadvantages of Enumeration
- An enum is not suitable when values are completely unrestricted.
- Traditional enums can cause naming conflicts.
- Traditional enums can convert to integers more easily than desired.
- Additional conversion may be required when using
enum classwith integers. - An enum represents a fixed set of named values, so it may not be suitable for frequently changing categories.
26. Common Errors
Error 1: Forgetting the Semicolon
Incorrect:
enum Color { RED, GREEN, BLUE }
Correct:
enum Color { RED, GREEN, BLUE };
Error 2: Incorrect enum class Access
Incorrect:
enum class Color { Red, Green }; Color c = Green;
Correct:
Color c = Color::Green;
Error 3: Direct Conversion from enum class
Incorrect:
enum class Color { Red, Green }; int x = Color::Green;
Correct:
int x = static_cast<int>(Color::Green);
Error 4: Duplicate Enumerator Names
This can cause a problem with traditional enums:
enum Color { RED, GREEN }; enum Traffic { RED, YELLOW };
A safer modern approach is:
enum class Color { RED, GREEN }; enum class Traffic { RED, YELLOW };
27. Important Points to Remember
- Enumeration is a user-defined data type.
- The keyword
enumis used to define a traditional enumeration. enum classcreates a scoped enumeration.- Enumeration contains a fixed set of named constants.
- Traditional enum values normally start from
0. - Values can be assigned manually.
- The next unassigned value normally continues from the previous value.
enum classvalues are accessed using::.enum classdoes not implicitly convert to integers.static_cast<int>()can be used for explicit conversion.- Enums are commonly used with
switch. enum classhelps avoid naming conflicts.- Enums are useful for representing states, categories, and choices.
28. Quick Syntax Reference
Traditional Enum
enum Color { RED, GREEN, BLUE };
Create Variable
Color color = GREEN;
Custom Values
enum Status { SUCCESS = 1, ERROR = 2, PENDING = 3 };
Scoped Enum
enum class Color { Red, Green, Blue };
Create Scoped Enum Variable
Color color = Color::Green;
Convert Scoped Enum to Integer
int value = static_cast<int>(color);
Switch with Enum Class
switch (color) { case Color::Red: // code break; case Color::Green: // code break; case Color::Blue: // code break; }
29. Traditional Enum vs Enum Class
| Feature | Traditional enum | enum class |
|---|---|---|
| Scope | Unscoped | Scoped |
| Syntax | enum Color | enum class Color |
| Access | RED | Color::RED |
| Type safety | Lower | Higher |
| Implicit integer conversion | Yes | No |
| Naming conflicts | More possible | Avoided |
| Modern C++ use | Supported | Generally preferred |
30. Complete Example Program
#include <iostream> using namespace std; enum class Day { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }; void displayDay(Day day) { switch (day) { case Day::Monday: cout << "Monday"; break; case Day::Tuesday: cout << "Tuesday"; break; case Day::Wednesday: cout << "Wednesday"; break; case Day::Thursday: cout << "Thursday"; break; case Day::Friday: cout << "Friday"; break; case Day::Saturday: cout << "Saturday"; break; case Day::Sunday: cout << "Sunday"; break; } } int main() { Day today = Day::Wednesday; cout << "Today is: "; displayDay(today); return 0; }
Output
Today is: Wednesday
31. Summary
An enumeration (enum) is a user-defined data type that represents a fixed set of named constants.
For example:
enum Color { RED, GREEN, BLUE };
By default:
RED = 0 GREEN = 1 BLUE = 2
C++ also provides a safer scoped form:
enum class Color { Red, Green, Blue };
which is used as:
Color c = Color::Green;
Enumeration is particularly useful for states, categories, options, directions, days, traffic lights, user roles, and other fixed sets of choices.
Conclusion
Enumeration makes C++ programs more readable and organized by replacing unexplained numeric values with meaningful names. Traditional enum is useful for simple cases, while enum class is generally preferable in modern C++ when stronger type safety and scoped names are desired.