Enum

Enumeration(enum) is a user-defined datatype (same as structure). It consists of various elements of that type. There is no such specific use of enum, we use it just to make our codes neat and more readable. We can write C programs without using enumerations also.

For example, Summer, Spring, Winter and Autumn are the names of four seasons. Thus, we can say that these are of type season. So this becomes an enumeration with name season and Summer, Spring, Winter and Autumn as its elements.

So, you are clear with the basic idea of enum. Now let's see how to define it.

Defining an Enum

An enum is defined in the same way as structure with the keyword struct replaced by the keyword enum and the elements separated by 'comma' as follows.

enum enum_name{
element1,
element2,
element3,
element4,};

Now let's define an enum of the above example of seasons.

enum Season{
Summer,
Spring,
Winter,
Autumn
};

Here, we have defined an enum with name 'Season' and 'Summer, Spring, Winter and Autumn' as its elements.

Declaration of Enum Variable

We also declare an enum variable in the same way as structures. We create an enum variable as follows.

Here, first, we defined an enum named 'Season' and declared its variable 's' in the main function as we have seen before. The values of Summer, Spring, Winter and Autumn are 0, 1, 2 and 3 respectively. So, by writing s = Spring, we assigned a value '1' to the variable 's' since the value of 'Spring' is 1.

We can also assign some value to an enum variable as shown in the following example.

In this example, we declared two enum variables s1 and s2. Here, we are declaring and assigning values to the variables at the same time. We are assigning values to the variables by two ways in this example.enum Season s1 = Spring; - This statement is assigning the value of Spring i.e. 1 to s1.enum Season s2(Winter); - This is the second way you can assign the value at the time of declaration. This statement is assigning the value of Winter i.e. 2 to s2.

We can also change the default value and assign any value of our choice to an element of enum. Once we change the default value of any enum element, then the values of all the elements after it will also be changed accordingly. An example will make this point clearer.

The default value of sun will be 0, mon will be 1, tue will be 2 and so on. In the above example, we defined the value of tue as 5. So the values of wed, thurs, fri and sat will become 6, 7, 8 and 9 respectively. There will be no effect on the values of sun and mon which will remain 0 and 1 respectively. Thus the value of thurs i.e. 7 will get printed.