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)

Fortran function can return allocatable characters. If you run into bugs with this on old compilers, try manually allocating the character variable. Fortran standard compliant compilers auto-allocate character functions like numeric arrays.

function greet(b)

logical, intent(in) :: b

character(:), allocatable :: greet

!! Manual allocation of character variable. This could be necessary on old or buggy compilers.

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

end function greet