Pascal Programming/Enumerations

From Wikibooks, open books for an open world
Jump to: navigation, search


Sometimes, programmers need a way of expressing ordinal values as names. A good example is Pascal's boolean type, which is essentially an enumeration type that holds the values False and True. We can make our own with the following.

  TMonth = ( Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec );

A variable declared as an enumeration type such as TMonth is restricted to using only those values. It is possible to explicitly typecast a record variable to an ordinal type, but this is impractical most of the time.

  month: TMonth;
  month := Mar;

Extensions and optimizations[edit]

C-style enumerations[edit]

Some compilers, such as Free Pascal, offer an enumeration syntax in the style of C's enums. That is, ordinal values may be associated with the constants declared in an enumeration.

  TMonth = ( Jan = 0, Feb, Mar, Apr = 45, May );

Note that, just like in C, ordinal values assigned to an enumeration's constants must be in order from least to greatest, otherwise the compiler will generate an error.