Tech

Enumeration–Functions–STRUCTURED PROGRAMMING Course Notes

Enumeration

Enumeration–an enumeration, introduced by the keyword ‘enum‘ and followed by a type name is a user-defined type.

An enumeration is a set of named integer constants represented by identifiers. The values of these enumeration constants start at 0, unless specified otherwise, and increment by 1.

A popular enumeration is:

  • enum Months { Jan = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };
    • where:
    • enum‘ is the ‘keyword
    • ‘Months’ is the ‘identifier
    • ‘JAN’ thru ‘DEC’ are the ‘enumeration constant names

…which creates user-defined type ‘Months’ with enumeration constants representing the months of the year. The first value is explicitly specified to start at 1, so the remaining values increment from 1, resulting in the values 1 through 12. (Any enumeration constant can be assigned an integer value in the enumeration definition, and subsequent enumeration constants each have a value 1 higher than the preceding constant in the list until the next explicit setting.)

Note: Capitalize the first letter of an identifier used as a user-defined type name.

Note: Use only UPPERCASE LETERS in enumeration constant names. This makes these constants stand out in a program and reminds us that enumeration constants are not variables.