Concepts of Programming Languages

(Sean Pound) #1

258 Chapter 6 Data Types


In the area of reliability, the enumeration types of Ada, C#, F#, and Java
5.0 provide two advantages: (1) No arithmetic operations are legal on enu-
meration types; this prevents adding days of the week, for example, and
(2) second, no enumeration variable can be assigned a value outside its defined
range.^4 If the colors enumeration type has 10 enumeration constants and
uses 0..9 as its internal values, no number greater than 9 can be assigned to
a colors type variable.
Because C treats enumeration variables like integer variables, it does not
provide either of these two advantages.
C++ is a little better. Numeric values can be assigned to enumeration type
variables only if they are cast to the type of the assigned variable. Numeric val-
ues assigned to enumeration type variables are checked to determine whether
they are in the range of the internal values of the enumeration type. Unfortu-
nately, if the user uses a wide range of explicitly assigned values, this checking
is not effective. For example,

enum colors {red = 1, blue = 1000, green = 100000}

In this example, a value assigned to a variable of colors type will only be
checked to determine whether it is in the range of 1..100000.

6.4.2 Subrange Types


A subrange type is a contiguous subsequence of an ordinal type. For example,
12..14 is a subrange of integer type. Subrange types were introduced by
Pascal and are included in Ada. There are no design issues that are specific to
subrange types.

6.4.2.1 Ada’s Design
In Ada, subranges are included in the category of types called subtypes. As was
stated in Chapter 5, subtypes are not new types; rather, they are new names
for possibly restricted, or constrained, versions of existing types. For example,
consider the following declarations:

type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
subtype Weekdays is Days range Mon..Fri;
subtype Index is Integer range 1..100;

In these examples, the restriction on the existing types is in the range of pos-
sible values. All of the operations defined for the parent type are also defined


  1. In C# and F#, an integer value can be cast to an enumeration type and assigned to the name
    of an enumeration variable. Such values must be tested with Enum.IsDefined method
    before assigning them to the name of an enumeration variable.

Free download pdf