Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants which make a program easy to read and maintain.
The keyword “enum” is used to declare an enumeration.
The following is the way to define the enum in C:
enum flag{integer_const1,
integer_const2,.....integter_constN};
In the above declaration, enum named as flag containing 'N'
integer constants is defined. The default value of integer_const1 is 0,
integer_const2 is 1, and so on.
If we do not explicitly assign values to enum names, the
compiler by default assigns values starting from 0.
Example:
enum fruits{mango, apple, banana, papaya};
The default value of mango is 0, apple is 1, banana is 2, and
papaya is 3.
To change these default values, then :
enum fruits{ mango=2, apple=1, banana=5, papaya=7};
Variables of type enum can also be defined. They can be defined in two ways:
enum week{Mon, Tue,
Wed};
enum week day;
// Or
enum week{Mon, Tue,
Wed}day;
An example program to
demonstrate working of enum in C
#include<stdio.h>
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
void main()
{
enum week day;
day = Wed;
printf("%d",day);
}
Example 2:
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5, wednesday,
thursday = 10, friday, saturday};
void main()
{
printf("%d %d %d %d %d %d %d", sunday, monday,
tuesday,wednesday, thursday, friday, saturday);
}
Output:
1 2 5 6 10 11 12
Note: We can assign values to some name in any order. All
unassigned names get value as value of previous name plus one.