On Tuesday, April 20, 2021 at 1:58:27 AM UTC-7,
arjen.m...@gmail.com wrote:
> Hello,
>
> I just came across a situation where it would be nice (though not essential) to have a lower bound of 0, while building up an array. Something like:
>
> newarray = [oldarray, newelement]
> write(*,*) newarray(0:)
allocate(newarray(0:size(oldarray)))
newarray = [oldarray, newelement]
to be more sure that it doesn't reallocate, or to make it more
obvious to readers:
allocate(newarray(0:size(oldarray)))
newarray(0:size(oldarray)) = [oldarray, newelement]
The ability to add elements to an array this way is convenient, but
not so efficient. It requires allocating and copying the whole array.
If you do this a lot, or deeply nested in loops, it is often worth allocating
a larger array and separately keeping track of the number of elements in use.
(I presume from the name that newelement is a scalar. If not, you need
to consider its size, too.)
I note that you didn't say:
oldarray = [oldarray, newelement]
It isn't so obvious what compilers might do with this, but one might create a
temporary array for the right side, copy data into it, reallocate oldarray,
and copy the data over. In that case, you might do better using movealloc().
Just to be sure, I am not suggesting premature optimization, but in case optimization
is needed, you know where to look for it.
Otherwise, array expressions always have a lower bound of 1.