C++ Enumeration
Enumeration, also known as an enum
, is a data type in C++ that allows you to define a set of named constant values. Enumeration is a useful tool for creating clear and concise code, as it provides a way to define a set of values that are easily recognizable and distinguishable from other variables in your program. In this article, we will explore the basics of enumeration in C++ and how to use it in your programs.
Declaring an Enumeration
To declare an enumeration in C++, you can use the enum
keyword followed by a set of constant values. For example, consider the following code that declares an enumeration Color
:
1enum Color { 2 RED, 3 GREEN, 4 BLUE 5};
In this example, we have declared an enumeration Color
with three constant values: RED
, GREEN
, and BLUE
. These values are represented as integers, with the first value RED
being assigned the value 0
, the second value GREEN
being assigned the value 1
, and so on.
Using an Enumeration
Once an enumeration has been declared, you can use it in your program by declaring a variable of the enumeration type and assigning it one of the constant values. For example, consider the following code:
1enum Color { 2 RED, 3 GREEN, 4 BLUE 5}; 6 7int main() { 8 Color favoriteColor = GREEN; 9 cout << "My favorite color is " << favoriteColor << endl; 10 return 0; 11}
Output:
My favorite color is 1
In this example, we have declared a variable favoriteColor
of type Color
and assigned it the value GREEN
. When we print the value of favoriteColor
to the console, we see that it is represented as the integer value 1
.
You can also assign values to enumeration constants explicitly by using the =
operator. For example, consider the following code:
1enum Color { 2 RED = 10, 3 GREEN = 20, 4 BLUE = 30 5}; 6 7int main() { 8 Color favoriteColor = GREEN; 9 cout << "My favorite color is " << favoriteColor << endl; 10 return 0; 11}
Output:
My favorite color is 20
In this example, we have assigned explicit values to the constants in the Color
enumeration. When we print the value of favoriteColor
to the console, we see that it is still represented as the integer value 20
.