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 example(str)
character(*), intent(in) :: str

Before Fortran 202X standard, intrinsic Fortran functions need traditional fixed length character variables. For example:

integer :: i, L
character(:), allocatable :: buf

call get_command_argument(1, length=L, status=i)
if (i /= 0) error stop "first command argument not available"
allocate(character(L) :: 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.

It is proper to manually allocate character variable actual arguments when bind(C) interfaces are used.

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