FORTRAN 95:OPTIONAL语句不起作用(使用FTN95和Plato)

gil*_*ofb 3 fortran subroutine optional plato

OPTIONAL在使用Fortran 95的函数和子程序中的语句有问题.目前我正在使用Silverfrost的Plato和他们的FTN95编译器(在"Release Win32"模式下).在我正在编写的更复杂的程序中尝试实现OPTIONAL语句之后,我创建了一个非常简单的程序来测试它.这是代码:

program TEST

implicit none
integer :: a=1, b=2

call Z(a,b)
call Z(a)
call Z(b)

end program TEST

subroutine Z(x,y)
implicit none
integer :: x
integer, optional :: y

if (present(y)) then
  write(*,*) x, y
  else
    write(*,*) x
endif

end subroutine Z
Run Code Online (Sandbox Code Playgroud)

我希望屏幕上显示以下结果:

1 2
1
2
Run Code Online (Sandbox Code Playgroud)

好吧,代码编译,虽然我得到一个警告(673)"SUBROUTINE Z被调用的参数太少".执行后,我进入我的屏幕:

1 2
Run Code Online (Sandbox Code Playgroud)

然后出现"访问冲突"错误消息.有人能理解这里有什么问题吗?

非常感谢!吉尔伯托

Jon*_*rsi 7

尝试将子例程放在一个模块中,如下所示:

module testoptional
contains
    subroutine Z(x,y)
    implicit none
    integer :: x
    integer, optional :: y

    if (present(y)) then
      write(*,*) x, y
      else
        write(*,*) x
    endif

    end subroutine Z
end module testoptional

program TEST
    use testoptional
    implicit none
    integer :: a=1, b=2

    call Z(a,b)
    call Z(a)
    call Z(b)

end program TEST
Run Code Online (Sandbox Code Playgroud)

然后编译并运行使用gfortran和ifort给出预期结果.

问题在于主程序如何知道(或猜测)接口Z(x,y).在你提供的代码中,虽然主程序和子程序在同一个文件中,但是没有明确告诉主程序接口 - 调用序列,包括参数计数,类型等等Z.第一个调用是Z(a,b),所以它推断出有一个子程序在那里需要两个参数; 然后它尝试使用一个参数调用它,该参数失败.

将子例程放在一个模块中,然后使用该模块(您也可以使用contains包含的子例程,或者使用interface块显式地/手动地为主程序提供接口)然后为主程序提供它需要的关于调用序列的信息 - 例如,有一个可选的参数 - 事情正常.