Array length: Difference between revisions
→{{header|Fortran}}: Aha, all is not as it appears...
(Frink) |
(→{{header|Fortran}}: Aha, all is not as it appears...) |
||
Line 184:
=={{header|Fortran}}==
Early fortrans offered no protocol for ascertaining the length (or dimensionality) of arrays, though the compiler
Later fortrans allowed <code>A(*)</code> to signify an array parameter of unstated
With Fortran 90, a new protocol was introduced, whereby the parameter might be declared as <code>A(:)</code> signifying an array of one dimension, of bounds unstated. A 2-D array would have <code>A(:,:)</code> and so on. Further, arrays could have arbitrary lower bounds as well, as in <code>A(-7:12)</code> but if no colon appeared for a dimension, the lower bound would be assumed to be one so <code>A(2)</code> means an array of two elements, as before. And as before, a bound could be explicitly stated, perhaps via an explicit parameter such as <code>N</code>, but now, the compiler is passing secret additional parameters to the subprogram giving the bounds of the array, and these can be accessed via the library functions LBOUND and UBOUND. For multi-dimensional arrays there are multiple bounds, and an invocation might be <code>UBOUND(A,DIM = 2)</code> but in the example only a one-dimensional array is involved. These facilities are available only if the new MODULE protocol is employed.
The task is in terms of an array holding the texts "Apple" and "Orange", so a CHARACTER*6 element size will do; the subprogram receives yet another secret parameter specifying the size of CHARACTER parameters. This size can be accessed via the LEN function, and, since in principle the index span is arbitrary, no constant index is sure to be a valid index of some single element: thus the LBOUND function is used to finger one that is.
Line 207:
PROGRAM SHOWBOUNDS
USE EXAMPLE
CHARACTER*6 ARRAY(
ARRAY(-1) = "Apple"
ARRAY(
ARRAY(1) = ""
CALL ABOUND(ARRAY)
WRITE (6,*) "But, when it is at home..."
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
END
</lang>
Output:
Lower bound 1 , Upper bound
Element size 6
Apple Orange
But, when it is at home...
L. bound -1 , U. bound 1
Notice that the subprogram sees the array as an old-style array starting with index one!
=={{header|FurryScript}}==
|