Loading, please wait...

Enumeration Constants

C provides one final user-defined type called an enumeration. An enumeration, introduced by the keyword enum, is a set of integer enumeration constants represented by identifiers. Values in an enum start with 0, unless specified otherwise, and are incremented by

 

For example, the enumeration

enum months {

JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

creates a new type, enum months, in which the identifiers are set to the integers 0 to 11, respectively. To number the months 1 to 12, use the following enumeration:

enum months {

JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC

};

 

 

Since the first value in the preceding enumeration is explicitly set to 1, the remaining values are incremented from 1, resulting in the values 1 through 12. The identifiers in an enumeration must be unique. The value of each enumeration constant of an enumeration can be set explicitly in the definition by assigning a value to the identifier. Multiple members of an enumeration can have the same constant value.

 

In the program of the enumeration variable month is used in a for a statement to print the months of the year

Example

/*Using an enumeration type */
#include <stdio.h>
/* enumeration constants represent months of the year */
enum months {
JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

int main( void )
{
enum months month; /* can contain any of the 12 months */

/* initialize array of pointers */
const char *monthName[] = { "", "January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December" };

/* loop through months */
For (month = JAN; month<= DEC; month++) {
printf( "%2d%11s\n", month, monthName[ month ] );
} /* end for */

return 0; /* indicates successful termination */
} /* end main */

Output:

1 January

2 February

3 March

4 April

5 May

6 June

7 July

8 August

9 September

10 October

11 November

12 December