In response to a question about character function results of non-constant length, an answer mentions \"assumed length function result\" but doesn\'t go into detail.
If
An assumed length character function looks like the following:
function assumed_len(x)
character(*), intent(in) :: x
character(*) :: assumed_len
assumed_len = x//'!'
end function
Here the dummy argument x
and the function result assumed_len
are both assumed length characters.
Much like how x
assumes its length from the actual argument when the function is referenced, the function result assumes its length from the function declaration in the referencing place.
With the above function, consider the program
implicit none
character(len=11) :: x='Hello world'
character(len=12) assumed_len
print *, assumed_len(x)
end
During the function's execution the function result has length 12 as declared in the main program. Equally, if we wanted it to have length 5 we simply change the declaration in the main program to character(len=5) assumed_len
. In a different program unit the declaration could be something different and the function result would assume that length when referenced.
Well, that doesn't look so harmful: why should we avoid using functions like this?
In summary:
In every other aspect of Fortran, the attributes of a function result depend only on the arguments of the function and other accessible information. Here the attributes of the function result may differ with everything else the same through a declaration in an unrelated scope.
To the other points:
In those cases where we really do want to control the length in the referencing place we can replace assumed_len
with a function with explicit length result like
function replacement(x, n)
character(*), intent(in) :: x
integer, intent(in) :: n
character(n) :: replacement
...
end function
or a subroutine with assumed length dummy argument
subroutine replacement(x, y)
character(*), intent(in) :: x
character(*), intent(out) :: y
...
end subroutine
Finally, assumed length character functions are declared obsolescent in the current Fortran standard, and may be deleted in later revisions.