An enumeration is a user-defined type that consists of a set of named integral constants. These constants are fixed constant. The keyword enum
is used to define these data types.
Syntax of enums
enum enum_name{const1, const2, ....... };
enum_name
: Name of the enum given by the user.const1, const2
: These are the value of type enum_name.
Let us see an example to define enum.
enum season { spring, summer, autumn, winter };
The above is the enum for the season, spring, summer, autumn
and winter
are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.
We can change the default values of enum and assign the required value in the following way.
enum season { spring = 01, summer = 04, autumn = 06, winter=09 };
How to declare an enum variable
We can declare an enum variable in two different ways:
- We can declare it at the time of defining enum, just add the enum variable name at the end and before the semicolon.
- Another way is we can create it inside the main function. Both ways are shown below.
1 2 3 4 5 6 7 8 9 10 | <strong>//first way</strong> enum enum_name{const1, const2, ....... } <em>variable_name</em>; <strong>//Second way</strong> enum enum_name{const1, const2, ....... }; int main() { enum_name variable_name; } |
Example of enumeration in c++
1. Let us see an example of enum in c++ with the first way of declaring variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include <iostream> using namespace std; enum week{ Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } today; int main() { today = Monday; cout << "Day: " << today+1; return 0; } |
Output:
//Output
Day: 2
2. Another example of enum, where we declare the variable inside the main function. Also, we change the default values of enums.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <iostream> using namespace std; enum colors{red = 12, green = 24, blue = 36}; int main() { colors color; color = green; cout << "Green: " << color; return 0; } |
Output:
//Output
Green: 24
Why use enum in C++
We use enum when we want to assign the variable with one of the possible sets of values. These values cannot be changed, if we try to assign different values to this variable the compiler generates an error. Thus, it improves safety and increases compile-time checking.
There is another use of enum that is in a switch case statement. Also, enum can be traversed.