C++ Enums
In C++, enums (short for enumerations) are a user-defined data type that consists of a set of named integer constants. They are used to represent a collection of related values, making code more readable and manageable. Enums help in defining a variable that can only take one out of a limited set of values.
1. Basic Syntax
An enumeration is defined using the enum keyword followed by a name and a list of named values enclosed in braces.
Example:
cppenum Color {
RED,
GREEN,
BLUE
};
In this example, Color is an enumeration type with three possible values: RED, GREEN, and BLUE. By default, the values are assigned integers starting from 0.
2. Customizing Values
You can assign specific values to the named constants in an enumeration.
Example:
cppenum Day {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
Here, MONDAY is explicitly set to 1, and the subsequent values will increment automatically (i.e., TUESDAY will be 2, WEDNESDAY will be 3, and so on).
3. Using Enums
You can declare variables of the enum type and assign them values from the enum list.
Example:
cpp#include
using namespace std;
enum Status {
SUCCESS,
FAILURE,
PENDING
};
int main() {
Status jobStatus = PENDING;
if (jobStatus == SUCCESS) {
cout << "Operation was successful!" << endl;
} else if (jobStatus == FAILURE) {
cout << "Operation failed!" << endl;
} else {
cout << "Operation is pending." << endl;
}
return 0;
}
4. Enum Classes (Scoped Enums)
In C++11, enum classes (also known as scoped enums) were introduced. They provide better type safety and prevent name clashes by creating a scoped enumeration.
Example:
cppenum class Fruit {
APPLE,
BANANA,
CHERRY
};
int main() {
Fruit myFruit = Fruit::APPLE;
if (myFruit == Fruit::APPLE) {
cout << "You have an apple." << endl;
}
return 0;
}
- Scoped enums require the use of the scope resolution operator (
::) to access the enumerators (e.g.,Fruit::APPLE). - They do not implicitly convert to integers, providing better type safety.
5. Underlying Type of Enums
In C++11 and later, you can specify the underlying type of an enum class, which determines the size of the enum values.
Example:
cppenum class ErrorCode : unsigned int {
OK = 0,
WARNING = 1,
ERROR = 2
};
ErrorCodeis an enum class withunsigned intas its underlying type.
6. Accessing Enum Values
To access or print the values of an enum class, you need to cast the enum value to its underlying type.
Example:
cpp#include
using namespace std;
enum class Level : int {
LOW = 1,
MEDIUM = 2,
HIGH = 3
};
int main() {
Level myLevel = Level::MEDIUM;
// Casting to print integer value
cout << "The level is: " << static_cast<int>(myLevel) << endl;
return 0;
}
7. Enum Iteration
C++ does not provide built-in iteration for enums. To iterate over enum values, you can use an array or a function.
Example:
cpp#include
using namespace std;
enum class Direction {
NORTH,
EAST,
SOUTH,
WEST
};
const char* directionToString(Direction dir) {
switch (dir) {
case Direction::NORTH: return "North";
case Direction::EAST: return "East";
case Direction::SOUTH: return "South";
case Direction::WEST: return "West";
default: return "Unknown";
}
}
int main() {
for (int i = static_cast<int>(Direction::NORTH); i <= static_cast<int>(Direction::WEST); i++) {
Direction dir = static_cast(i);
cout << directionToString(dir) << endl;
}
return 0;
}
Summary:
Basic Enums:
- Use the
enumkeyword to define enumerations with named constants. - Values start from 0 by default and increment automatically unless specified.
- Use the
Custom Values:
- Assign specific integer values to the enumerators if needed.
Enum Classes:
- Use
enum classfor better type safety and scoped enumerations. - Access enumerators with the scope resolution operator (
::).
- Use
Underlying Type:
- Specify an underlying type for enum classes to control the storage size.
Accessing and Printing:
- Use casting to access or print enum values.
Iteration:
- Use arrays or functions to iterate over enum values, as C++ does not provide built-in iteration for enums.
Enums improve code readability by providing meaningful names for integer values, making it easier to understand and maintain code.