我发现这段代码出乎意料
module testmodule
integer, parameter :: LCHARS = 50
contains
subroutine init()
call foobar("foobar")
end subroutine
subroutine foobar(s)
character(len=*), intent(in) :: s
call bar(s)
end subroutine
subroutine bar(str)
character(len=LCHARS), intent(in) :: str
print *, str
end subroutine
end module
program foo
use testmodule
call init()
end program
Run Code Online (Sandbox Code Playgroud)
此代码打印依赖于编译器的垃圾.
我发现问题在于我正在跳过一个带有len=*字符串参数的例程,然后将其传递给字符串参数的指定长度的例程.
正是在幕后发生了什么,标准中描述的这种行为在哪里?我是否应该避免为字符例程参数指定长度,因为这种行为可能在任何时候发生而没有警告?
我认为你的代码不符合要求.第12.4.1.1Fortran 95条标准规定:
12.4.1.1与虚拟数据对象关联的实际参数
[...]
如果标量伪参数的类型为默认字符,则伪参数的长度len应小于或等于实际参数的长度.伪参数与实际参数的最左边的len个字符相关联.