Summary
This chapter describes the main composite types which are arrays and records. It also completes our discussion of enumeration types by introducing characters and strings. At this stage we discuss arrays fairly completely but consider only the simplest forms of records. Tagged records and interfaces which permit extension and polymorphism are discussed in Chapter 14 and discriminated records which include variant records are deferred until Chapter 18. Tasks and protected types which are also classified as composite are discussed in Chapter 20.
Arrays
An array is a composite object consisting of a number of components all of the same type (strictly, subtype). An array can be of one, two or more dimensions. A typical array declaration might be
A: array (Integer range 1 .. 6) of Float;
This declares A to be a variable object which has six components, each of which is of type Float. The individual components are referred to by following the array name with an expression in parentheses giving an integer value in the discrete range 1 .. 6. If this expression, known as the index value, has a value outside the bounds of the range, then the exception Constraint_Error will be raised. We could set zero in each component of A by writing
for I in 1 .. 6 loop
A(I) := 0.0;
end loop;
An array can be of several dimensions, in which case a separate range is given for each dimension. So
AA: array (Integer range 0 .. 2, Integer range 0 .. 3) of Float;
is an array of 12 components in total, each of which is referred to by two integer index values, the first in the range 0 .. 2 and the second in the range 0 .. 3. The components of this two-dimensional array could all be set to zero by a nested loop thus
for I in 0 .. 2 loop
for J in 0 .. 3 loop
AA(I, J) := 0.0;
end loop;
end loop;
The discrete ranges do not have to be static; one could have
N: Integer := … ;
B: array (Integer range 1 .. N) of Boolean;
and the value of N at the point when the declaration of B is elaborated would determine the number of components in B.
- Type
- Chapter
- Information
- Programming in Ada 2012 , pp. 117 - 148Publisher: Cambridge University PressPrint publication year: 2014