Fortran

Guide To Learn

Checking for allocation status

It will, at times, be useful to know the allocation status of a variable; that is, whether it’s currently allocated or not. To do this, we can use the built-in allocated function, as shown in the following listing.

Listing 5.9 Checking for allocation status

real, allocatable :: a(:)
print *, allocated(a)      ❶
allocate(a(10))
print *, allocated(a)      ❷
deallocate(a)
print *, allocated(a)      ❸

❶ Will print F

❷ Will print T

❸ Will print F

Trying to allocate an already allocated variable, or to deallocate a variable that’s not allocated, will trigger a runtime error.

Tip Always check for allocation status before explicitly allocating or deallocating a variable.

Checking for allocation status

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top