Concepts of Programming Languages

(Sean Pound) #1
6.4 User-Defined Ordinal Types 255

operations are slowed by the required pointer chasing. On the other hand,
using adjacent memory for complete strings results in faster string operations
and requires significantly less storage, but the allocation and deallocation pro-
cesses are slower.

6.4 User-Defined Ordinal Types


An ordinal type is one in which the range of possible values can be easily
associated with the set of positive integers. In Java, for example, the primitive
ordinal types are integer, char, and boolean. There are two user-defined
ordinal types that have been supported by programming languages: enumera-
tion and subrange.

6.4.1 Enumeration Types


An enumeration type is one in which all of the possible values, which are
named constants, are provided, or enumerated, in the definition. Enumeration
types provide a way of defining and grouping collections of named constants,
which are called enumeration constants. The definition of a typical enumera-
tion type is shown in the following C# example:

enum days {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

The enumeration constants are typically implicitly assigned the integer
values, 0, 1,... but can be explicitly assigned any integer literal in the type’s
definition.
The design issues for enumeration types are as follows:


  • Is an enumeration constant allowed to appear in more than one type defi-
    nition, and if so, how is the type of an occurrence of that constant in the
    program checked?

  • Are enumeration values coerced to integer?

  • Are any other types coerced to an enumeration type?
    All of these design issues are related to type checking. If an enumeration
    variable is coerced to a numeric type, then there is little control over its range
    of legal operations or its range of values. If an int type value is coerced to an
    enumeration type, then an enumeration type variable could be assigned any
    integer value, whether it represented an enumeration constant or not.


6.4.1.1 Designs
In languages that do not have enumeration types, programmers usually simu-
late them with integer values. For example, suppose we needed to represent
colors in a C program and C did not have an enumeration type. We might use
Free download pdf