Hi, I am new to fortran, and I’m playing with different compilers.
I find something I can’t explain, gfortran give different answers with intel’s compiler for the following program.
Does it make sense?
function f(str) result(alen)
character(*) :: str
character(len=len(str)), allocatable :: str2
integer :: alen
allocate(str2)
str2 = str
alen = len(str2)
end function
program aa
interface
function f(str) result(alen)
character(*) :: str
integer :: alen
end function
end interface
Anyway, whether your syntax is valid or not, it seems that gfortran has a bug here: it should either report a compilation error or give the right result.
PS: please format your code by enclosing it beetween triple backticks, i.e. (the </> button at the top of the editor will also do, after you select your code):
character(len=len(str)), allocatable :: str2
is allowed because len(str) is a valid specification expression by virtue of the fact that str is a dummy argument that has neither the OPTIONAL nor the INTENT(OUT) attribute and LEN is an intrinsic inquiry function. It could also be written as str%len (a type-parameter-inquiry), if the compiler supports it.
I see no reason this program would be considered invalid, and it ought to behave as you probably expect. That said, it is an unusual example/style, and is mixing several features not commonly seen together in ways that are redundant, so not surprised by any bugs you find in compilers with it.
For example, you could remove the allocatable attribute and allocate statement, and the program would likely work fine. This makes str2 an “automatic” variable.
On the other hand you could change len(str) in the declaration to :, and either omit the allocate statement (to get automatic allocation on assignment) or change it to allocate(character(len=len(str)) :: str2). This has become the more common way since this feature was introduced.
Intel’s compiler gives the answer I expect, that is length of the string.
Different versions of gfortran give different answers.
Sometimes it gives random integers, sometimes the program backtraces.
I am not sure why you need str2 at all, unless you are testing allocatable character strings ?
The following works with Gfortran ( after correcting printf as posted )
It could be better to have f in CONTAINS
function f(str) result(alen)
character(*) :: str
character(len=len(str)), allocatable :: str2
integer :: alen
allocate(str2)
str2 = str
alen = len(str2)
end function
integer function slen (str)
character(*) :: str
slen = len(str)
end function slen
program aa
interface
function f(str) result(alen)
character(*) :: str
integer :: alen
end function f
integer function slen (str)
character(*) :: str
end function slen
end interface
print *, f ( 'sdfsdf' )
print *, slen ( 'sdfsdf' )
! pause
end program
Also check your print statement, I changed: print *, f(“sdfsdf”)
to : print *, f ( ‘sdfsdf’ )
as your " may be another unicode character.