Welcome to The Coding College! In this tutorial, we’ll explore enumerations in C++, also known as enum
. Enumerations are a powerful feature in C++ that allow you to define a set of named integral constants, making your code more readable and maintainable.
What Is an Enumeration (enum) in C++?
An enumeration is a user-defined data type consisting of a set of named constants called enumerators. By using enums, you can assign meaningful names to a set of integer values, which makes your code easier to understand.
Syntax
enum EnumName {
ENUM_VALUE1,
ENUM_VALUE2,
ENUM_VALUE3,
// ...
};
EnumName
: The name of the enumeration.ENUM_VALUE1
,ENUM_VALUE2
, …: The enumerators, representing unique constant values.
Example: Basic Enumeration
#include <iostream>
using namespace std;
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
int main() {
Day today = Wednesday;
if (today == Wednesday) {
cout << "It's Wednesday!" << endl;
}
return 0;
}
Output:
It's Wednesday!
How Enumerations Work
- Enumerators are assigned integer values starting from
0
by default. - You can explicitly assign values to enumerators if needed.
- Enumerations make code more readable and prevent the use of arbitrary numbers.
Assigning Custom Values
You can assign specific integer values to enumerators.
Example: Custom Values
#include <iostream>
using namespace std;
enum ErrorCode {
Success = 0,
NotFound = 404,
PermissionDenied = 403
};
int main() {
ErrorCode code = NotFound;
cout << "Error code: " << code << endl; // Prints 404
return 0;
}
Output:
Error code: 404
Scoped Enumerations (enum class)
In C++11 and later, scoped enumerations were introduced using the enum class
keyword. They provide better type safety and avoid unintentional implicit conversions to integers.
Syntax
enum class EnumName {
ENUM_VALUE1,
ENUM_VALUE2
};
Example: Scoped Enumeration
#include <iostream>
using namespace std;
enum class Color {
Red,
Green,
Blue
};
int main() {
Color favoriteColor = Color::Green;
if (favoriteColor == Color::Green) {
cout << "Green is your favorite color!" << endl;
}
return 0;
}
Output:
Green is your favorite color!
Comparing enum
and enum class
Feature | enum | enum class |
---|---|---|
Scope | Global | Scoped (within enum class ) |
Implicit Conversion | Can be implicitly converted to integers | No implicit conversion |
Type Safety | No | Yes |
Syntax | enum Name | enum class Name |
Using Enumerations in Switch Statements
Enumerations work seamlessly with switch
statements, providing a clear and readable way to handle cases.
Example: Enum in a Switch Statement
#include <iostream>
using namespace std;
enum TrafficLight {
Red,
Yellow,
Green
};
int main() {
TrafficLight signal = Green;
switch (signal) {
case Red:
cout << "Stop!" << endl;
break;
case Yellow:
cout << "Caution!" << endl;
break;
case Green:
cout << "Go!" << endl;
break;
default:
cout << "Invalid signal!" << endl;
}
return 0;
}
Output:
Go!
Applications of Enumerations
- Error Codes: Represent application-specific error codes.
- State Machines: Track states in a finite-state machine.
- Traffic Lights: Model systems like traffic signals.
- Days of the Week: Assign constants to weekdays for scheduling.
- User Roles: Define user access levels in a program (e.g., Admin, Editor, Viewer).
Best Practices for Using Enumerations
- Use Descriptive Names: Make enumerator names meaningful and self-explanatory.
- Prefer
enum class
: Scoped enumerations prevent unintentional type conversions and offer better type safety. - Avoid Overlapping Values: Ensure enumerator values don’t conflict unless explicitly intended.
- Combine With Constants: Use enums for grouping related constants for better organization.
Real-Life Example: User Roles
#include <iostream>
using namespace std;
enum class UserRole {
Admin = 1,
Editor = 2,
Viewer = 3
};
int main() {
UserRole user = UserRole::Editor;
switch (user) {
case UserRole::Admin:
cout << "Access granted: Admin privileges." << endl;
break;
case UserRole::Editor:
cout << "Access granted: Editor privileges." << endl;
break;
case UserRole::Viewer:
cout << "Access granted: Viewer privileges." << endl;
break;
default:
cout << "Invalid role!" << endl;
}
return 0;
}
Output:
Access granted: Editor privileges.
Learn More at The Coding College
Enumerations are just one of many features in C++ that simplify and organize code. For more in-depth tutorials on C++ and other programming concepts, visit The Coding College.