Search code examples
fortran

How do I write to an allocatable character variable?


I have a subroutine that's essentially a logger. It takes in a required string, as well as two optional parameters that it formats.

Here's a simplified version. Currently this fails when writing to action_local

subroutine log(required_param, action, idx)
    character(len=*), intent(in) :: required_param
    character(len=*), intent(in), optional :: action
    integer, intent(in), optional :: idx
    character(:), allocatable :: action_local

10  format(A, A, I)

    if (present(action) .and. present(idx)) then
        write(action_local, 10) ' ', action, idx ! fails: action_local is not allocated
    else
        action_local = ''
    end if

    print *, required_param // action_local
end subroutine

Ideally I wouldn't guess at the size required - I'd just let the output of the write statement allocate what it needs. Is there a way to write to an allocatable character without allocating it ahead of time?


Solution

  • In a Fortran 2023 write statement, an internal file which is an allocatable deferred-length scalar character variable is defined according to the rules of intrinsic assignment. This includes first allocating it to the correct length if required.

    That is, in the form of the question

    write(action_local, 10) ' ', action, idx
    

    the action_local is the internal file, and it's indeed scalar, allocatable and deferred-length. There is no need to allocate it before the data transfter statement.

    You don't have a Fortran 2023 compiler.

    You will need to allocate its length first (such as in your own answer) or manually use intrinsic assignment (such as using the various techniques found in answer elsewhere).