Pass string as argument when dummy pointer has length

if i have this code

module test
contains
   subroutine xx(name)
      character(len=20), intent(in), optional :: name

      if (present(name)) then
         print *, name
      else
         print *, "foo"
      endif
   end subroutine
end module
program x
   use test

   call xx()
   call xx("foo2")
end program

It will not compile since "foo2" has no length 20, and the compiler complains

test.f90(17): error #7938: Character length argument mismatch.   ['foo2']
   call xx("foo2")
-----------^

How can I make this work without changing the specification of the dummy len subroutine? Is it necessary to have an intermediate variable declared with the same length and pass it during the call?

+3
source share
3 answers

. , @kemiisto (dummy arg) <= length ( arg). (dummy arg) = 20 length (actual arg) = 4, (dummy arg) > length (actual arg), . , , .

, character(len = 20) character(len = *) , ?

+6

, .

Fortran 2003, 12.4.1.2 ,

, len . .

gfortran

: , 'name' (4/20) at (1)

, Intel Fortran . , , , .

, . . , . =)

+2

, / len=20 name. , . intent(in), ..

, len=* len len_trim , /.

, len=20, , . - , "hello"//repeat(" ", 15).

+1

Source: https://habr.com/ru/post/1787393/


All Articles