If you assign an array to an allocatable array variable, the target array variable is automatically allocated with the correct size to match the array on the right side. The array variable can be already allocated or not. If it is, it will be reallocated if its current size differs from that of the source array. For example, try appending elements to an array on the fly, as shown in the following listing.
Listing 5.8 Automatically reallocating an array on assignment
integer, allocatable :: a(:)
a = [integer ::] ❶
a = [a, 1] ❷
a = [a, 2] ❸
a = [a, 2 * a] ❹
This feature is particularly useful when trying to assign an array that is a result of a function, and whose size is not known ahead of time. We’ll use this feature often in this book.
There’s an important difference between explicit allocation with the allocate statement and allocation on assignment. The former will trigger a runtime error if issued twice–that is, if you issue an allocate statement on an object that’s already allocated. On the other side, the latter will gracefully reallocate the array if already allocated. To be able to effectively reuse dynamic arrays, Fortran gives us a counterpart to the allocate statement that allows us to explicitly clear the object from memory.