Enumeration in C
Enumeration is a derived data type similar to a structure or a union Its members are constants that are written as identifiers, though they have signed integer values Enumeration constants are automatically assigned equivalent integer values. An enumeration is a user-defined data type consists of integral constants and each integral constant is give a name. Keyword enum is used to defined enumerated data type.
Its first member values start with 0 and are incremented by 1 also we can set values explicitly with using equal to operator (=).
Syntax of enumeration in C is given below.
enum type_name {
member1,
member 2,
… . ,
member n
};
Enumeration variables can be declared as given below.
storage-class-type enumtype_name var1, var2 ;
Example of enumeration in C
enum days{
SUN,
MON,
TUE,
WED,
THU,
FRE,
SAT
};
Here enumeration constants are
SUN 0 MON 1 TUE 2 WED 3 THU 4 FRI 5 SAT 6
Also we can assign explicit values to enumeration constants like given below.
enum days{
SUN = 10,
MON = 11,
TUE = 12,
WED = 13,
THU = 14,
FRE = 15,
SAT = 16
};
In above example enumeration constants are
SUN 10 MON 11 TUE 12 WED 13 THU 14 FRI 15 SAT 16
See an example C program
#include <stdio.h>
enum days{ sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days today;
today = wednesday;
printf(“%d day”,today);
return 0;
}
Output:
$ ./a.out
3