Concepts of Programming Languages

(Sean Pound) #1

412 Chapter 9 Subprograms


size of the dimensions of all arrays that are used as parameters at the time subpro-
grams are compiled. In Ada, unconstrained array types can be formal parameters.
An unconstrained array type is one in which the index ranges are not given in the
array type definition. Definitions of variables of unconstrained array types must
include index ranges. The code in a subprogram that is passed an unconstrained
array can obtain the index range information of the actual parameter associated
with such parameters. For example, consider the following definitions:

type Mat_Type is array (Integer range <>,
Integer range <>) of Float;
Mat_1 : Mat_Type(1..100, 1..20);

A function that returns the sum of the elements of arrays of Mat_Type
type follows:

function Sumer(Mat : in Mat_Type) return Float is
Sum : Float := 0.0;
begin
for Row in Mat'range(1) loop
for Col in Mat'range(2) loop
Sum := Sum + Mat(Row, Col);
end loop; -- for Col...
end loop; -- for Row...
return Sum;
end Sumer;

The range attribute returns the subscript range of the named subscript of
the actual parameter array, so this works regardless of the size or index ranges
of the parameter.
In Fortran, the problem is addressed in the following way. Formal param-
eters that are arrays must have a declaration after the header. For single-
dimensioned arrays, the subscripts in such declarations are irrelevant. But for
multidimensional arrays, the subscripts in such declarations allow the compiler
to build the storage-mapping function. Consider the following example skeletal
Fortran subroutine:

Subroutine Sub(Matrix, Rows, Cols, Result)
Integer, Intent(In) :: Rows, Cols
Real, Dimension(Rows, Cols), Intent(In) :: Matrix
Real, Intent(In) :: Result

...
End Subroutine Sub


This works perfectly as long as the Rows actual parameter has the value used
for the number of rows in the definition of the passed matrix. The number
of rows is needed because Fortran stores arrays in column major order. If the
array to be passed is not currently filled with useful data to the defined size,
Free download pdf