Beliavsky / FortranTip

Short instructional Fortran codes associated with Twitter @FortranTip
https://zmoon.github.io/FortranTipBrowser/
The Unlicense
64 stars 14 forks source link

Tip: assumed type argument #38

Open Beliavsky opened 2 years ago

Beliavsky commented 2 years ago

Fortran 2018 allows assumed type arguments that have no declared type, with syntax type(*). Such arguments can only be used in a small number of intrinsic functions, including SHAPE, SIZE, and RANK. Actual arguments can have intrinsic or derived types.

module test_assumed_type_mod
implicit none
contains
pure function same_shape(x,y) result(tf)
! assumed type, assumed rank arguments
type(*), intent(in) :: x(..),y(..)
logical             :: tf
if (rank(x) /= rank(y)) then
   tf = .false. ! not same shape if ranks differ
else
   tf = all(shape(x) == shape(y))
end if
end function same_shape
end module test_assumed_type_mod
!
program test_assumed_type
use test_assumed_type_mod, only: same_shape
implicit none
type :: date
   integer :: year, month, day
end type date
integer    :: i(2),j(2,1)
real       :: x(2)
logical    :: b(3)
type(date) :: d(2)
print*,same_shape(i,x),same_shape(i,b), &
       same_shape(x,b),same_shape(i,d)
print*,same_shape(j,i),same_shape(j,x)
end program test_assumed_type
! output with gfortran and Intel Fortran:
! T F F T
! F F