Yes. Here's an example. Note that an explicit interface is required - your function either needs to be a module procedure, an internal procedure (as is here) or have an interface block in the calling scope.
[fxfortran]! Compile with /standard-semantics
! Syntax to declare a deferred length character variable.
CHARACTER(:), ALLOCATABLE :: s
! Length of s automatically set based on the length of the function
! result. The function result is allocatable - behind the scenes it
! will be deallocated automatically at the end of the "innermost
! executable construct" (here that's the program itself).
s = function_that_returns_char_string()
PRINT *, s
! You could explicitly deallocate s if you wanted to, or let it be cleaned
! up automatically when it goes out of scope.
FUNCTION function_that_returns_char_string() RESULT(str)
! Function result
CHARACTER(:), ALLOCATABLE :: str
! Local variables
REAL :: r
INTEGER :: str_length
str_length = CEILING(r * 26.0)
! Length of str automatically set based on the length of the right
! hand side of the assignment statement.
str = 'abcdefghijklmnopqrstuvwxyz'(:str_length)
! Alternatively - you could explicitly allocate the length...
! ALLOCATE( CHARACTER(str_length) :: str )
! str(:) = 'abc...'
END FUNCTION function_that_returns_char_string
END PROGRAM dynamically_allocated_char[/fxfortran]
Thanks for the code sample, it worked has expected. However what happen to the allocated string (str)in the function: [fortran]FUNCTION function_that_returns_char_string() RESULT(str)[/fortran]once the result has been affected to the variable s ? [fortran]s = function_that_returns_char_string()[/fortran]In my case I don't want to affect the result but I'd rather print directly the string.
The function result (the thing called str inside the function body) is deallocated automatically at the end of the innermost executable construct that contains the function call. For this example, that's the end of the program.
(In this case, it doesn't really matter when that automatic deallocation happens, as it doesn't affect the program - the compiler could arrange for it to happen as soon as the assignment statement finished executing, or it could be clever and simply transfer the allocation from the result to the s variable, but that's implementation detail.)