Enumerations or enum in C
For Complete YouTube Video: Click Here
In this class, we will understand Enumerations or enum in C.
We have discussed the concepts of comments.
Table of Contents
Enumerations or enum in C
Example 1
Enumerations are used to assign names to integral constants, making a program easy to read and maintain.
The image below shows the definition of enumerations.
We have created two enumerations, boolean and weeks.
The wrong and right are provided as the names for integer constants, but where are the integers?
How do enumerations work?
By default, the first name in the definition is provided a value of 0. The second name provided a value of one so on so forth.
The image below shows how the integer constants are provided with names in the enumerations.
Let us try to understand the concept of enumerations in depth by using the example shown below.
In the above example, 0 is provided the name Mon, and one is provided the name Tue, so on.
But we want to assign Mon to 1, and 2 to Tue and so on.
We have created a variable day for enumeration week, and the day is assigned Wed.
When we print, day two will get published.
The default assignments can be changed, as shown below.
enum weeks = {Mon=1, Tue, Wed, Thu, Fri, Sat, Sun};
Now one is assigned to Mon, and Two is set to Tue, so on.
For example, we want to assign a ‘ten’ integer with Thu’s name.
Check the code below.
enum weeks = {Mon = 1, Tue, Wed, Thu = 10, Fri, Sat, Sun};
Now, one is assigned Mon; two is assigned Tue; Three is assigned Wed; ten is assigned Thu; eleven is assigned Fri and so on.
Example 2
The image below shows example 2 on enumerations.
In the above example, the names assigned to the integer constants are used to iterate the ‘for loop.’