Enumerations (Enums) in C++
An enumeration (enum
) is a user-defined data type consisting of integral constants assigned with names. Enums make code more readable and maintainable by replacing numeric constants with meaningful names.
Defining an Enum
Syntax
enum EnumName {
CONSTANT1,
CONSTANT2,
// ...
};
Example: Defining and Using an Enum
#include <iostream>
enum Direction {
NORTH,
EAST,
SOUTH,
WEST
};
int main() {
Direction dir = SOUTH;
if (dir == SOUTH) {
std::cout << "Heading South" << std::endl;
}
return 0;
}
Assigning Specific Values
You can assign specific integer values to enum constants.
Example: Enum with Specific Values
enum Weekday {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
Key Takeaways
- Enums associate names with integral constants.
- Improve code readability by using meaningful names.
- By default, the first constant is assigned 0, and the rest increment by 1.
Strongly Typed Enums (C++11)
C++11 introduced enum class
for better type safety.
Example: Using enum class
enum class Color {
RED,
GREEN,
BLUE
};
int main() {
Color myColor = Color::GREEN;
if (myColor == Color::GREEN) {
std::cout << "Color is Green" << std::endl;
}
return 0;
}
Key Takeaways
enum class
provides scoped and strongly typed enums.- Prevents implicit conversions to integers.
- Access enum constants using the scope resolution operator (
::
).