Concepts of Programming Languages

(Sean Pound) #1
6.5 Array Types 259

for the subtype, except assignment of values outside the specified range. For
example, in

Day1 : Days;
Day2 : Weekdays;

Day2 := Day1;

the assignment is legal unless the value of Day1 is Sat or Sun.
The compiler must generate range-checking code for every assignment to
a subrange variable. While types are checked for compatibility at compile time,
subranges require run-time range checking.
One of the most common uses of user-defined ordinal types is for the
indices of arrays, as will be discussed in Section 6.5. They can also be used for
loop variables. In fact, subranges of ordinal types are the only way the range of
Ada for loop variables can be specified.

6.4.2.2 Evaluation
Subrange types enhance readability by making it clear to readers that variables
of subtypes can store only certain ranges of values. Reliability is increased with
subrange types, because assigning a value to a subrange variable that is outside
the specified range is detected as an error, either by the compiler (in the case of
the assigned value being a literal value) or by the run-time system (in the case
of a variable or expression). It is odd that no contemporary language except
Ada has subrange types.

6.4.3 Implementation of User-Defined Ordinal Types


As discussed earlier, enumeration types are usually implemented as integers.
Without restrictions on ranges of values and operations, this provides no
increase in reliability.
Subrange types are implemented in exactly the same way as their parent
types, except that range checks must be implicitly included by the compiler in
every assignment of a variable or expression to a subrange variable. This step
increases code size and execution time, but is usually considered well worth the
cost. Also, a good optimizing compiler can optimize away some of the checking.

6.5 Array Types


An array is a homogeneous aggregate of data elements in which an individual
element is identified by its position in the aggregate, relative to the first ele-
ment. The individual data elements of an array are of the same type. References
to individual array elements are specified using subscript expressions. If any of
the subscript expressions in a reference include variables, then the reference
Free download pdf