C++ enum
An enum
in C++ is a user-defined data type that defines a set of named integer constants. It provides a way to create symbolic names for a group of related values, making code more readable and maintainable. Enums are particularly useful when representing a fixed set of options or states in the program.
Syntax of C++ enum
enum enum_name {
constant1,
constant2,
constant3,
...
};
Parameters:
enum_name
: The name of the enumeration typeconstant1, constant2, constant3, ...
: Named constants within the enum
Return value:
Enums do not return values directly. They define a new data type that can be used to create variables.
Example 1: Basic Enum Creation in C++
This example demonstrates how to create a simple enum and use it in a program:
#include <iostream>using namespace std;// Define an enum for days of the weekenum Day {MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY};int main() {// Create an enum variableDay today = WEDNESDAY;// Output the enum valuecout << "Today is day number: " << today << endl;return 0;}
The output of this code is:
Today is day number: 2
In this example, an enum called Day
is defined with seven constants representing days of the week. By default, MONDAY
receives the value 0, TUESDAY
gets 1, and so on. A variable today
of type Day
is created and assigned the value WEDNESDAY
, which holds the integer value 2.
Example 2: Changing Values in Enum
This example shows how to assign custom values to enum constants:
#include <iostream>using namespace std;// Define an enum with custom valuesenum Priority {LOW = 1,MEDIUM = 5,HIGH = 10,URGENT = 15};int main() {// Create enum variablesPriority taskPriority = HIGH;Priority alertLevel = URGENT;// Display the valuescout << "Task priority: " << taskPriority << endl;cout << "Alert level: " << alertLevel << endl;// Compare enum valuesif (alertLevel > taskPriority) {cout << "Alert level is higher than task priority" << endl;}return 0;}
The output of this code is:
Task priority: 10Alert level: 15Alert level is higher than task priority
This example demonstrates how to assign specific integer values to enum constants. When a value is set for one constant, subsequent constants automatically increment from that value unless explicitly assigned. In this case, LOW
is 1, MEDIUM
is 5, HIGH
is 10, and URGENT
is 15.
Example 3: Enum in a Switch Statement
This example demonstrates using enums with switch statements for control flow:
#include <iostream>using namespace std;// Define an enum for traffic light colorsenum TrafficLight {RED,YELLOW,GREEN};int main() {TrafficLight currentLight = RED;// Use enum in switch statementswitch (currentLight) {case RED:cout << "Stop! Red light is on." << endl;break;case YELLOW:cout << "Caution! Yellow light is on." << endl;break;case GREEN:cout << "Go! Green light is on." << endl;break;default:cout << "Unknown light state." << endl;}// Simulate traffic light sequencecout << "\nTraffic light sequence:" << endl;for (int i = RED; i <= GREEN; i++) {TrafficLight light = static_cast<TrafficLight>(i);switch (light) {case RED:cout << "RED -> ";break;case YELLOW:cout << "YELLOW -> ";break;case GREEN:cout << "GREEN";break;}}cout << endl;return 0;}
The output generated by this code is:
Stop! Red light is on.Traffic light sequence:RED -> YELLOW -> GREEN
This example shows how enums work perfectly with switch statements, providing clear and readable control flow. The enum values make the code self-documenting and easier to maintain than using magic numbers.
Codebyte Example: Create Enum Class
This example demonstrates scoped enums (enum
class) introduced in C++ 11, which provide better type safety and scope control:
The text provides information about the strengths of the Enum class compared to regular enums. Key advantages include strong typing, which avoids implicit conversion to integers, reduced namespace pollution, and prevention of naming conflicts. Accessing enum class values requires the use of the scope resolution operator (::
).
Frequently Asked Questions
1. Why use enum instead of array?
Enums are used to define a set of named constants that represent fixed values, while arrays store collections of data. Enums provide compile-time constants that make code more readable and maintainable. Unlike arrays, enums don’t allocate memory for storing values at runtime - they’re purely symbolic names for integer constants.
2. How to get enum value in C++?
You can get the integer value of an enum by simply using the enum constant in an integer context or by explicitly casting it. For regular enums, implicit conversion to int works, but for enum classes, you need static_cast<int>(enum_value)
.
3. Can enum values be strings?
No, enum values in C++ are always integers. However, you can create arrays or maps to associate enum values with strings for display purposes.
4. What’s the difference between enum and enum class?
enum
class (scoped enums) introduced in C++11 provides better type safety, doesn’t pollute the namespace, and prevents implicit conversions. Regular enums allow implicit conversion to integers and their constants are accessible without scope resolution.
All contributors
- MamtaWardhani
- Arinze_Obi
- Christine_Yang
- garanews
- Anonymous contributor
- yekyam
- Prince25
- christian.dinh
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours