enum EnumName {
VALUE1,
VALUE2,
VALUE3
};Enumerations in C++: Defining Named Constant Values With enum
Direct Answer & Core Concept
In C++, programs often work with a fixed set of related values. For example, an application may need to represent days of the week, months, traffic light signals, payment statuses, or user roles.
You could use integers or strings to represent these values, but doing so can make programs harder to understand and maintain.
C++ provides a feature called enumeration (enum) that allows you to define a collection of named constant values.
For example, instead of writing 1, 2, and 3 to represent different order statuses, you can define meaningful names such as Pending, Processing, and Completed.
Detailed Explanation & Mechanics
1. What Is an Enumeration in C++?
An enumeration is a user-defined type that represents a set of named constant values.
Each name is called an enumerator.
Syntax
Here:
enumis the keyword used to declare an enumeration.EnumNameis the name of the enumeration type.VALUE1,VALUE2, andVALUE3are enumerators.The semicolon after the closing brace is required.
Example: Declare an Enumeration
#include <iostream>
using namespace std;
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
Day today = Wednesday;
cout << today;
return 0;
}Output:
2By default, the first enumerator has the value 0, and each following enumerator increases by one.
| Enumerator | Default value |
|---|---|
Monday | 0 |
Tuesday | 1 |
Wednesday | 2 |
Thursday | 3 |
Friday | 4 |
Saturday | 5 |
Sunday | 6 |
The output is 2 because Wednesday has the underlying value 2.
Although the value can be displayed as an integer, using meaningful enumerator names makes the program easier to read.
2. Declaring and Initializing enum Variables
After defining an enumeration, you can create variables of that type.
Syntax
EnumName variableName;Example:
enum Color {
Red,
Green,
Blue
};
Color selectedColor = Green;Here, selectedColor is an enumeration variable containing the value Green.
You can also assign another enumerator:
selectedColor = Blue;A traditional unscoped enum can also be declared and used directly:
enum Status {
Pending,
Approved,
Rejected
};
Status orderStatus = Pending;3. Assigning Custom Values to Enumerators
By default, enumerators receive consecutive integer values starting from zero. You can also assign your own values.
Example
#include <iostream>
using namespace std;
enum Level {
Low = 1,
Medium = 5,
High = 10
};
int main() {
Level currentLevel = High;
cout << "Level value: " << currentLevel;
return 0;
}Output:
Level value: 10In this example:
Lowhas the value1.Mediumhas the value5.Highhas the value10.
If an enumerator is not explicitly assigned a value, it normally receives one greater than the previous enumerator.
Example:
enum Number {
First = 10,
Second,
Third,
Fourth = 20,
Fifth
};The values are:
| Enumerator | Value |
|---|---|
First | 10 |
Second | 11 |
Third | 12 |
Fourth | 20 |
Fifth | 21 |
4. Using enum With switch Statements
Enumerations work particularly well with switch statements because each enumerator represents a named option.
Example: Display Days of the Week
#include <iostream>
using namespace std;
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
Day today = Friday;
switch (today) {
case Monday:
cout << "Start of the working week";
break;
case Friday:
cout << "End of the working week";
break;
case Saturday:
case Sunday:
cout << "Weekend";
break;
default:
cout << "Regular working day";
}
return 0;
}Output:
End of the working weekThe switch statement checks the enumeration value and executes the matching case.
Using named values is clearer than writing numeric case labels such as 0, 1, or 2.
5. Comparing enum Values
You can compare values of the same enumeration type using comparison operators.
Example
#include <iostream>
using namespace std;
enum Priority {
Low,
Medium,
High
};
int main() {
Priority task = High;
if (task == High) {
cout << "High priority task";
} else {
cout << "Other priority";
}
return 0;
}Output:
High priority taskYou can use operators such as:
==for equality.!=for inequality.<for less than.>for greater than.<=for less than or equal to.>=for greater than or equal to.
These comparisons use the enumerators' underlying values. Use them only when the numeric ordering is meaningful for your application.
6. What Is enum class in C++?
C++11 introduced scoped enumerations, declared using enum class or enum struct.
They provide stronger type safety and avoid placing enumerator names directly into the surrounding scope.
Syntax
enum class EnumName {
VALUE1,
VALUE2,
VALUE3
};Example: Using enum class
#include <iostream>
using namespace std;
enum class Color {
Red,
Green,
Blue
};
int main() {
Color selectedColor = Color::Green;
if (selectedColor == Color::Green) {
cout << "Green color selected";
}
return 0;
}Output:
Green color selectedNotice the syntax:
Color::GreenWith enum class, you must qualify enumerators using the enumeration type name.
Advantages of enum class
Provides stronger type safety.
Keeps enumerator names inside their enumeration scope.
Prevents implicit conversion to integers.
Reduces accidental name conflicts.
Makes code easier to understand in larger applications.
For most new C++ code, enum class is generally the preferred choice.
7. Difference Between enum and enum class
Traditional unscoped enums and scoped enums have some important differences.
| Feature | enum | enum class |
|---|---|---|
| Introduced | Traditional C++ | C++11 |
| Enumerator scope | Surrounding scope | Enumeration scope |
| Implicit conversion to integer | Supported | Not supported |
| Type safety | Less restrictive | Stronger |
| Name conflicts | More likely | Less likely |
| Access syntax | Red | Color::Red |
| Underlying type | Implementation-selected integral type | Implementation-selected integral type |
Example: Traditional enum
enum Color {
Red,
Green,
Blue
};
Color selected = Green;
int value = selected;The conversion to int is allowed.
Example: enum class
enum class Color {
Red,
Green,
Blue
};
Color selected = Color::Green;
// int value = selected; // Compilation errorYou must explicitly convert a scoped enumerator when an integer value is needed.
int value = static_cast<int>(selected);8. Specifying the Underlying Type of an Enumeration
C++ allows you to specify the integral type used to represent an enumeration.
This is useful when you need a particular representation or a defined range.
Syntax
enum class EnumName : data_type {
VALUE1,
VALUE2
};Example
#include <iostream>
using namespace std;
enum class Status : unsigned char {
Pending = 1,
Approved = 2,
Rejected = 3
};
int main() {
Status current = Status::Approved;
cout << static_cast<int>(current);
return 0;
}Output:
2Here, unsigned char is the specified underlying type.
The explicit conversion is needed because enum class values do not automatically convert to integers.
You can also specify an underlying type for a traditional enum:
enum Status : unsigned char {
Pending = 1,
Approved = 2,
Rejected = 3
};9. Forward Declaration of an enum
A scoped enumeration can be declared before its full definition, provided its underlying type is known or specified as required by the language rules.
Example
#include <iostream>
using namespace std;
enum class Status : int;
void displayStatus(Status value);
enum class Status : int {
Pending,
Approved,
Rejected
};
void displayStatus(Status value) {
if (value == Status::Approved) {
cout << "Approved";
}
}
int main() {
displayStatus(Status::Approved);
return 0;
}Output:
ApprovedForward declarations are useful when organizing declarations across multiple source files or headers.
10. Using enum for Bit Flags
Enumerations can also represent sets of independent options using bit flags.
This is commonly done with scoped enumerations and bitwise operators.
Example
#include <iostream>
using namespace std;
enum class Permission : unsigned int {
None = 0,
Read = 1,
Write = 2,
Execute = 4
};
int main() {
Permission access =
static_cast<Permission>(
static_cast<unsigned int>(Permission::Read) |
static_cast<unsigned int>(Permission::Write)
);
unsigned int flags = static_cast<unsigned int>(access);
if ((flags & static_cast<unsigned int>(Permission::Read)) != 0) {
cout << "Read permission enabled" << endl;
}
if ((flags & static_cast<unsigned int>(Permission::Write)) != 0) {
cout << "Write permission enabled" << endl;
}
if ((flags & static_cast<unsigned int>(Permission::Execute)) != 0) {
cout << "Execute permission enabled" << endl;
}
return 0;
}Output:
Read permission enabled
Write permission enabledEach flag uses a different bit:
| Permission | Value | Binary representation |
|---|---|---|
| None | 0 | 000 |
| Read | 1 | 001 |
| Write | 2 | 010 |
| Execute | 4 | 100 |
The bitwise OR operation combines permissions. The bitwise AND operation checks whether a particular flag is present.
For larger applications, you can define overloaded bitwise operators to make flag handling easier to read.
11. Using enum in Functions
Enumeration values can be passed to functions like other variables.
Example
#include <iostream>
using namespace std;
enum class TrafficLight {
Red,
Yellow,
Green
};
void displaySignal(TrafficLight signal) {
switch (signal) {
case TrafficLight::Red:
cout << "Stop";
break;
case TrafficLight::Yellow:
cout << "Get Ready";
break;
case TrafficLight::Green:
cout << "Go";
break;
}
}
int main() {
displaySignal(TrafficLight::Green);
return 0;
}Output:
GoUsing an enumeration as a function parameter makes the expected set of values clear.
12. Using enum in Structures and Classes
Enumerations can be used as data members in structures and classes.
Example: Employee Department
#include <iostream>
#include <string>
using namespace std;
enum class Department {
HR,
IT,
Finance,
Sales
};
struct Employee {
int id;
string name;
Department department;
};
int main() {
Employee emp = {
101,
"Amit",
Department::IT
};
cout << "Employee ID: " << emp.id << endl;
cout << "Employee Name: " << emp.name << endl;
if (emp.department == Department::IT) {
cout << "Department: IT";
}
return 0;
}Output:
Employee ID: 101
Employee Name: Amit
Department: ITThis approach is useful when records need to store values selected from a fixed set of options.
13. enum vs const vs constexpr
C++ provides several ways to represent constant values. They serve different purposes.
| Feature | enum | const | constexpr |
|---|---|---|---|
| Main purpose | Define named related values | Prevent modification of an object through that name | Define values usable in constant expressions when initialized appropriately |
| Multiple related values | Yes | Individual declarations | Individual declarations or related constants |
| User-defined type | Yes | No | No |
| Type safety | Stronger with enum class | Depends on declared type | Depends on declared type |
| Common use | Status, category, direction | Values that must not be modified | Compile-time constants |
Example: const
const int maxUsers = 100;Example: constexpr
constexpr int maxSize = 50;Example: enum class
enum class Status {
Pending,
Approved,
Rejected
};Use an enumeration when you have a fixed group of named alternatives. Use const or constexpr for individual constant values.
14. Real-World Applications of Enumerations in C++
Enumerations are useful in many software applications.
Order Management Systems
Represent order states such as Pending, Processing, Shipped, and Delivered.
Banking Applications
Represent transaction types such as Deposit, Withdrawal, and Transfer.
Game Development
Represent game states, player actions, directions, and difficulty levels.
Traffic Control Systems
Represent traffic light states such as Red, Yellow, and Green.
Employee Management Systems
Represent departments, employment types, or role categories.
Network Applications
Represent connection states, request types, and protocol options.
15. Common Mistakes When Using enum
Mistake 1: Using an Enumerator Outside Its Scope
With enum class, this is incorrect:
enum class Color {
Red,
Green
};
Color selected = Green; // Compilation errorUse the qualified name:
Color selected = Color::Green;Mistake 2: Assigning an Integer Directly to enum class
Incorrect:
enum class Status {
Pending,
Approved
};
Status current = 1; // Compilation errorUse a named enumerator:
Status current = Status::Approved;If you genuinely need a conversion, use an explicit cast after validating the value.
Mistake 3: Assuming Enumerator Values Always Start From Zero
An unscoped or scoped enumeration can use explicitly assigned values.
enum Status {
Pending = 10,
Approved = 20,
Rejected = 30
};Do not assume the first value is always zero.
Mistake 4: Reusing Enumerator Names in the Same Scope
Traditional unscoped enums introduce their enumerator names into the surrounding scope. Reusing the same name can cause a compilation error.
Using enum class helps avoid this problem.
Mistake 5: Using enum When a Dynamic Set Is Needed
An enumeration is appropriate for a fixed set of named alternatives. If values need to be created dynamically at runtime, a different data structure may be more suitable.
16. Best Practices for Using Enumerations
Prefer
enum classfor new C++ code.Use meaningful enumerator names.
Specify an underlying type when a particular representation is required.
Avoid relying on implicit integer conversions.
Use
switchstatements to handle distinct enumeration values.Include a suitable default or handle all expected cases.
Use distinct powers of two for bit flags.
Avoid using raw numeric values when named enumerators are available.
Keep enumeration definitions close to the types and functions that use them.
Use enumerations for fixed sets of related values, not arbitrary user-generated data.
17. Frequently Asked Questions (FAQs)
1. What is an enum in C++?
An enum is a user-defined type that defines a set of named constant values.
2. Which keyword is used to declare an enumeration?
The enum keyword is used to define an enumeration in C++.
3. What is the default starting value of an enum?
The first enumerator has the value 0 by default. Each subsequent enumerator normally receives a value one greater than the previous one.
4. Can we assign custom values to enum members?
Yes. You can assign explicit integral values to enumerators.
5. What is enum class in C++?
enum class is a scoped, strongly typed enumeration introduced in C++11. It prevents enumerator names from being injected into the surrounding scope and does not implicitly convert to integers.
6. What is the difference between enum and enum class?
Traditional enum values are unscoped and can implicitly convert to integers. enum class values are scoped and require explicit conversion when an integer is needed.
7. Can we use enum with switch statements?
Yes. Both traditional enums and scoped enums can be used in switch statements.
8. Can we compare enum values?
Yes. Values of the same enumeration type can be compared using operators such as ==, !=, <, and >.
9. Can an enum have a custom underlying type?
Yes. You can specify an integral type:
enum class Status : unsigned char {
Pending,
Approved
};10. Can we use enum inside a structure?
Yes. An enumeration can be used as a data member in a structure or class.
11. Can enum be used for bit flags?
Yes. Enumerations can represent independent bit flags using powers of two and bitwise operations.
12. Which is better: enum or enum class?
For most modern C++ programs, enum class is preferred because it provides better scope control and stronger type safety.
Runnable Code Example: Enumerations in C++
C++20 / C++23#include <iostream>
#include <cstdint>
// Scoped enum with explicit underlying type uint8_t
enum class NetworkState : uint8_t {
Disconnected = 0,
Connecting = 1,
Connected = 2,
Error = 255
};
void checkState(NetworkState state) {
if (state == NetworkState::Connected) {
std::cout << "Network is healthy and connected.
";
} else {
std::cout << "Network state code: " << static_cast<int>(state) << "
";
}
}
int main() {
NetworkState current = NetworkState::Connected;
checkState(current);
NetworkState err = NetworkState::Error;
checkState(err);
std::cout << "Enum storage size: " << sizeof(current) << " byte
";
return 0;
}