Pascal Programming/Enumerations
< Pascal ProgrammingEnumerations
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.
type
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.
var
month: TMonth;
begin
month := Mar;
end;
Extensions and optimizations
C-style enumerations
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.
type
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.