Fortran character allocatable

Variable length strings are implemented in Fortran 2003 standard like:

character(:), allocatable :: str

Passing such variables to procedures is declared the same as fixed length strings. In fact, we always declare actual arguments with “*” to avoid needing every string an exact length.

subroutine my(str)
character(*), intent(in) :: str

Note that intrinsic Fortran functions need traditional fixed length character variables. For example:

character(1000) :: buf

call get_command_argument(1, buf)

Functions can also return allocatable characters, with the caveat that some compilers like Nvidia HPC currently require the variable be manually allocated. Other compilers auto-allocate character functions like numeric arrays in Fortran 2003 code.

function greet(b)
logical, intent(in) :: b
character(:), allocatable :: greet

!! only nvfortran needs manual allocation

if(b) then
  allocate(character(5) :: greet)
  greet = 'hello'
  allocate(character(3) :: greet)
  greet = 'bye'

end function greet