C Enumeration

C Enumeration or Enumerated Data Type

C enumeration is a user defined data type which consists of a list of names and each name corresponds to an integral constant. It increases the program readability as names are easy to read and maintain. Enumerated data type can be defined in C using “enum” keyword. The syntax is given below.

Syntax

enum identifier_name {name1, name2, . . . . namen};

Example

enum day {mon, tue, wed, thu, fri, sat, sun};

In above example we have defined an enumerated data type day. Now we have to declare variables of this data type. The variables can store any name present in the list of names. The variables can be declared in following way.

enum day first_day, last_day;
first_day = mon;
last_day = sun;

Above we have declared two variables. The variable can also be declared at the time of defining the enumerated data type. For doing this just write the variable name after the closing braces and before the semicolon.

As I have already told you that each name in the list corresponds to an integral value. By default the integral value starts with 0. In above example “mon” will corresponds to 0, “tue” will corresponds to 1, “wed” will corresponds to 2 and so on. We can also assign random integral values explicitly. It can be done in following way.

enum day {mon=5, tue=7, wed=8, thu=10, fri=15, sat=25, sun=19}; //example 1
enum day {mon=2, tue, wed, thu, fri, sat, sun}; //example 2

In first example I have assigned random values to each name. In second example I have assigned value to only first name i.e. mon=2. The rest names will be assigned values that increased successively by 1. Remember that the values must be integer only and two names can have same value.

Lets make one program to understand the concept of C enumerated data type.

#include<stdio.h>

void main()
{
 enum day{mon,tue,wed,thu,fri,sat,sun};
 enum day d1,d2;
 d1=tue;
 d2=thu;
 printf("%d",d1);
 printf("n%dn",d2+2);
}

Output

C Enumeration - Enumerated Data Type

Explanation

  1. First of all I have declared an enumerated data type day which contains list of names of days in a week.
  2. As I have not assigned values to these names explicitly so the compiler will assign them values starting from 0.
  3. Now I have declared two variables d1 and d2 of this enumerated data type and assigned them names from the name list.
  4. Now I am printing the variables. In first printf() statement the output is 1 because d1 contains “tue” and it corresponds to integer value 1.
  5. In second printf() statement the variable d2 contains “thu” which corresponds to integer value 3. As I have written d2+2 so it will be equal to 5.

This is all about C enumeration. If you have any doubts or find any mistake in above tutorial then please mention it by commenting below.

Leave a Comment

Your email address will not be published. Required fields are marked *