C++ enums
Created By: chatGPT
In C++, enums (short for enumerations) are a user-defined type that consist of integral constants. They enable you to define a variable that can hold a set of predefined values, thus increasing the readability and maintainability of your code. Let's explore how to declare and use enums in C++.
enum Color {
RED,
GREEN,
BLUE
};
In the above example, we declare an enum named Color with three constants: RED, GREEN, and BLUE. By default, the first enum constant is assigned the value 0, the second constant 1, and so on. You can also specify custom values if needed.
enum Color {
RED = 1,
GREEN = 3,
BLUE = 5
};
Once you've defined an enum, you can create variables of that type. This not only restricts the values that can be assigned to the variable but also improves the clarity of your code.
Color myColor = GREEN;
Enums can also be used in switch statements, which can make your code cleaner and easier to understand. Here's an example of using an enum in a switch statement.
switch (myColor) {
case RED:
cout << "Red selected";
break;
case GREEN:
cout << "Green selected";
break;
case BLUE:
cout << "Blue selected";
break;
}
Starting from C++11, you can use a strongly typed enum (also known as enum class), which provides better type safety. This means that the enumerators do not implicitly convert to integers, preventing clashes between different enums.
enum class Vehicle {
CAR,
TRUCK,
MOTORCYCLE
};
To demonstrate how to use a strongly typed enum, you need to use the enum name along with its enumerator when referring to its values.
In summary, enums are a powerful feature in C++ that enhances code clarity and safety. They allow you to define a variable that can hold a set of predefined constant values, making your code more structured and readable.Vehicle myVehicle = Vehicle::CAR;