08 Feb C++ Enum
Enums stand for enumerations, i.e., a group of constants. Use enums to name constants. In this lesson, let us learn what is Enum in C++. We will cover the following concepts:
- What is Enum
- Create an Enum
- Create an Enum variable
- Assign a value to an Enum variable
- Example of Enum
What is Enum
We studied some types in C++. However, there is another type in C++ called enum (short for Enumeration).
Enum is a user-defined type that consists of a set of named integer constants. It is used to assign names to the integral constants, which makes a program easier to read and maintain.
1 2 3 4 5 6 7 8 9 10 11 |
enum enum_name { enum_item1, enum_item2, enum_item3, . . . enum_itemn }; |
Above, we have the enum name after the enum keyword. Then comes the enum items separated by a comma.
Create an Enum
Let us now see how to create an enum. We will consider Directions and enum items as NORTH, SOUTH, etc.:
1 2 3 4 5 6 7 8 |
enum Directions { NORTH, SOUTH, EAST, WEST }; |
Create an Enum variable
Create a variable of the Enum if you want to access it.
Let us create a variable of the above enum:
1 2 3 |
enum Directions d1; |
Assign a value to an Enum variable
On assigning a value to the enum, the resultant value will display an increment based on the enum items i.e…
By default, the values of the enumeration starts from, 0 and increase 1 for each subsequent enumerator.
Note: You can also assign custom values to the enumerators
Example of Enum
Let us now see an example of creating an Enum in C++. We will also assign value to the enum items, and display.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Enum in C++ // Code by Studyopedia #include <iostream> using namespace std; enum Directions { NORTH, SOUTH, EAST, WEST }; int main() { // Create enum variables Directions d1, d2; // Assign value d1 = NORTH; cout << d1 << endl; d2 = SOUTH; cout << d2 << endl; return 0; } |
Here is the output:
1 2 3 4 |
0 1 |
The above C++ code demonstrates the use of an enumeration (enum) to define a custom type called Directions, with possible values: NORTH, SOUTH, EAST, and WEST. Within the main function, two variables d1 and d2 of type Directions are declared. The code assigns NORTH to d1 and SOUTH to d2, and then prints their integer values. By default, NORTH is 0, SOUTH is 1, EAST is 2, and WEST is 3.
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments