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


Example


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.


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.


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.


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 *