4.6. Enumeration and Enumerators

An enumeration defines the name of a group of related values and the name of each value within the group. For example, the group COLOR and the colors within the group: RED, BLUE, and GREEN. The enumerator is a member of the group (for example, RED, BLUE, and GREEN). These names can enhance the readability and maintainability of your code.

In Fortran, an enumeration is an integer type-alias. The enumerator is a named integer constant of the same type. Since enumerators are all of the same integer type, kind values can be specified for them as a group. Hence, enumerators and integers of the same kind are interchangeable.

Fortran enumeration also allows you to access enumeration defined in C and use them as you would normally use a Fortran enumeration.

This is the form for enum_alias_def (enumerations):

Table 4-19.

 

enum_def

is

enum_def_stmt
   enumerator_def_stmt
   [ enumerator_def_stmt ] ...
end_enum_stmt

 

enum_def_stmt

is

ENUM, BIND(C) :: type_alias_name

 

 

or

ENUM [  kind_selector ] [ :: ] 
  type_alias_name

 

enumerator_def_stmt

is

ENUMERATOR [ :: ] enumerator_list

 

enumerator

is

named_constant  [ =
scalar_int_initialization_expr ]

 

end_enum_stmt

is

END ENUM [ type_alias_name ]

These notes apply to enumerations:

The format of an enumeration when a kind is specified is shown below:

 ENUM kind_selector ::  type_alias_name
      ENUMERATOR [ :: named_constant  = scalar_int_initialization_expr ]
      ...
   END ENUM [ type_alias_name ]

Enumerators are treated as though they were declared with type type_alias_name and the PARAMETER attribute.

If you do not explicitly assign each enumerator a value, the compiler assigns a value according to these rules:

This example shows how to declare enumerations:

IMPLICIT NONE
ENUM (KIND=1) :: COUNT
      ENUMERATOR :: ZERO, ONE, TWO
END ENUM COUNT

ENUM :: COLORS
      ENUMERATOR :: PURPLE
      ENUMERATOR :: RED = 2, BLUE = 5
      ENUMERATOR GREEN
END ENUM

TYPE (COUNT) :: COUNTING
INTEGER (KIND=1) :: NUMBER

NUMBER = TWO

The enumeration definitions for COUNT and COLOR show that enumerators can be defined in a single statement or in multiple statements. The order of the enumerators are important if the values are not assigned explicitly. For example, if GREEN was defined first, its value would be zero rather than six.

The above example also shows that enumerators and integers of the same kind can be used interchangeably (NUMBER = TWO).

Enumerations are equivalent to type aliases of the same type specification. For example, these type alias statements are equivalent to the COUNT enumeration definition:

TYPEALIAS :: COUNT => INTEGER (KIND = 1)
TYPE (COUNT), PARAMETER :: ZERO = 0, ONE = 1, TWO = 2
TYPE (COUNT) :: NUMBER