mabalenk
mabalenk

Reputation: 1043

Fortran wrapper for character functions trim(), adjustl()

I have written a simple wrapper for convenient use of Fortran intrinsic functions 'trim()' and 'adjustl()':

character(len=*) FUNCTION trimadjl(str)

character(len=*), intent(inout) :: str

trimadjl = trim(adjustl(str))

END FUNCTION

However, I'm unable to use it, since the GNU Fortran compiler fails with the following message:

farm_par.f90:633:31:

19    OPEN(iout,file=TRIMADJL(rankstr//fout),access='sequential',status='unknown', &
                           1
Warning: Non-variable expression in variable definition context (actual argument to INTENT = OUT/INOUT) at (1) farm_par.f90:633:22:

19    OPEN (iout,file=TRIMADJL(rankstr//fout),access='sequential',status='unknown', &
                  1
Error: Function ‘trimadjl’ is declared CHARACTER(*) and cannot be used at (1) since it is not a dummy argument

The function is declared as external in the header of the subroutine:

character(len=*), external :: trimadjl

Upvotes: 1

Views: 2258

Answers (1)

Modern Fortran has allocatable deferred-length character strings for this:

FUNCTION trimadjl(str)
character(len=:), allocatable :: trimadjl
character(len=*), intent(in) :: str

trimadjl = trim(adjustl(str))

END FUNCTION

Such a function cannot be external, place it into a module. See also Fortran character-returning function of unknown length

As @HighPerformanceMark comments, the first error message comes from you marking the dummy argument str as intent(inout) and then you pass an expression into it. rankstr//fout is a compound expression and cannot be passed into intent(inout) function, because it is not a variable. Use intent(in) arguments in functions wherever possible.

Don't use character(*) returning function unless you really know what that means in detail! Avoid them wherever possible. They are obsolete and very confusing. See "Assumed-length Character Functions" in http://fortranwiki.org/fortran/show/Modernizing+Old+Fortran. Don't use them and maybe even forget that they exist.

Upvotes: 3

Related Questions