The code below, lightly modified from this, surprised me. I did not know that you can pass an array or scalar variable that is not allocated
to a procedure as an optional argument and ask there whether it is present
. If not allocated
it is not present
. This language feature was discussed at the Intel Forum, where the last post, by Bálint_A_, gives its motivation.
module m
implicit none
contains
pure integer function mysize(x)
class(*), intent(in), optional :: x(..)
mysize = -1
if (present(x)) mysize = size(x)
end function mysize
!
pure integer function mysize_vec(x)
integer, intent(in), optional :: x(:)
mysize_vec = -1
if (present(x)) mysize_vec = size(x)
end function mysize_vec
end module m
program main
use m, only: mysize, mysize_vec
implicit none
integer, allocatable :: a(:), b(:), i
allocate(a(10))
print*, mysize(a), mysize(b)
print*, mysize_vec(a), mysize_vec(b)
print*, mysize(i)
allocate(i)
print*, mysize(i)
end program main
output:
10 -1
10 -1
-1
1