2.13.2 Enumerations

Defining symbolic names for constants in a program eases readability and simplifies the process of maintaining the program in the future. One method is to define an enumeration, which associates a set of integers with a set of identifiers called enumerators that the compiler recognizes and replaces with the corresponding integer value. An enumeration is defined by using a declaration such as the following:

enum colors {

The first enumerator in the enumeration, RED, is assigned the value zero and each subsequent identifier is assigned the next integer value.

You can also specify an explicit integer value for any enumerator by suffixing it with an equal sign and an integer constant, as shown in the following example:

enum colors {
  RED = 7,
  GREEN = 9,

The enumerator BLUE is assigned the value 10 by the compiler because it has no value specified and the previous enumerator is set to 9. When an enumeration is defined, the enumerators can be used anywhere in a D program that an integer constant is used. In addition, the enumeration enum colors is also defined as a type that is equivalent to an int. The D compiler allows a variable of enum type to be used anywhere an int can be used and will allow any integer value to be assigned to a variable of enum type. You can also omit the enum name in the declaration, if the type name is not needed.

Enumerators are visible in all subsequent clauses and declarations in your program. Therefore, you cannot define the same enumerator identifier in more than one enumeration. However, you can define more than one enumerator with the same value in either the same or different enumerations. You may also assign integers that have no corresponding enumerator to a variable of the enumeration type.

The D enumeration syntax is the same as the corresponding syntax in ANSI C. D also provides access to enumerations that are defined in the operating system kernel and its loadable modules. Note that these enumerators are not globally visible in your D program. Kernel enumerators are only visible if you specify one as an argument in a comparison with an object of the corresponding enumeration type. This feature protects your D programs against inadvertent identifier name conflicts, with the large collection of enumerations that are defined in the operating system kernel.

The following example D program displays information about I/O requests. The program uses the enumerators B_READ and B_WRITE to differentiate between read and write operations:

    printf("%8s %10s: %d %16s (%s size %d @ sect %d)\n",
    	args[1]->dev_statname, probename,  
    	timestamp, execname,  
    args[0]->b_flags & B_READ ? "R" : 
    args[0]->b_flags & B_WRITE ? "W" : "?",
    args[0]->b_bcount, args[0]->b_blkno);