C++ Enumeration Type
C++ Enumeration Type
An enumeration type in C++ allows you to define a set of named constants as a new data type. Each constant within the enumeration type represents a unique value that can be used in your code. Here are the steps to define and use an enumeration type in C++:
- Define the enumeration type: To define an enumeration type, you use the
enum
keyword followed by the name of the enumeration type. Inside the curly braces{}
, you list the names of the constants separated by commas. For example:
enum Color {
RED,
GREEN,
BLUE
};
In this example, we define an enumeration type called Color
with three constants: RED
, GREEN
, and BLUE
.
- Declare variables of the enumeration type: Once you have defined the enumeration type, you can declare variables of that type. For example:
Color myColor = GREEN;
In this example, we declare a variable myColor
of type Color
and initialize it with the constant GREEN
.
- Assign values to the constants: By default, the constants in an enumeration type are assigned integer values starting from 0. In the example above,
RED
will have the value 0,GREEN
will have the value 1, andBLUE
will have the value 2. You can also explicitly assign values to the constants. For example:
enum Day {
MONDAY = 1,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
};
In this example, we define an enumeration type called Day
and assign values to the constants. MONDAY
is assigned the value 1, and the subsequent constants are assigned the values 2, 3, and so on.
- Access the constants: You can access the constants in an enumeration type using the dot operator (
.
) with the name of the constant. For example:
Color myColor = GREEN;
if (myColor == RED) {
// Do something
}
In this example, we compare the value of myColor
with the constant RED
using the equality operator (==
).
- Switch statement: An enumeration type is often used in conjunction with a switch statement to perform different actions based on the value of a variable of that type. For example:
Color myColor = GREEN;
switch (myColor) {
case RED:
// Do something for red color
break;
case GREEN:
// Do something for green color
break;
case BLUE:
// Do something for blue color
break;
default:
// Handle other cases
break;
}
In this example, we use a switch statement to perform different actions based on the value of myColor
.
That's it! These are the steps to define and use an enumeration type in C++. Enumeration types are useful when you have a fixed set of values that a variable can take, such as days of the week, colors, or error codes. They provide a way to make your code more readable and maintainable by using meaningful names for the constants.