Fortran 引用程序
示例
为了使函数或子例程有用,必须对其进行引用。子程序在call语句中被引用
call sub(...)
以及表达式中的函数。与许多其他语言不同,表达式不能形成完整的语句,因此函数引用通常出现在赋值语句中或以其他方式使用:
x = func(...) y = 1 + 2*func(...)
有三种方法可以指定要引用的过程:
作为过程或过程指针的名称
派生类型对象的过程组件
类型绑定过程绑定名称
第一个可以看作是
procedure(), pointer :: sub_ptr=>sub call sub() ! With no argument list the parentheses are optional call sub_ptr() end subroutine sub() end subroutine
最后两个是
module mod type t procedure(sub), pointer, nopass :: sub_ptr=>sub contains procedure, nopass :: sub end type contains subroutine sub() end subroutine end module use mod type(t) x call x%sub_ptr() ! Procedure component call x%sub() ! Binding name end
对于带有伪参数的过程,该引用需要相应的实际参数,尽管可能未提供可选的伪参数。
考虑子程序
subroutine sub(a, b, c) integer a, b integer, optional :: c end subroutine
这可以通过以下两种方式引用
call sub(1, 2, 3) ! Passing to the optional dummy c call sub(1, 2) ! Not passing to the optional dummy c
这就是所谓的位置引用:实际参数是根据参数列表中的位置进行关联的。在这里,虚拟a对象与关联1,b与2和一起c(如果指定)与3。
或者,当过程具有可用的显式接口时,可以使用关键字引用
call sub(a=1, b=2, c=3) call sub(a=1, b=2)
与上述相同。
但是,使用关键字时,实际参数可以按任何顺序提供
call sub(b=2, c=3, a=1) call sub(b=2, a=1)
位置引用和关键字引用都可以使用
call sub(1, c=3, b=2)
只要在关键字首次出现后为每个参数指定关键字
call sub(b=2, 1, 3) ! Not valid: all keywords must be specified
当有多个可选的伪参数的关键字引用的值特别明显,如图低于如果在子程序定义的上方b也可选
call sub(1, c=3) ! Optional b is not passed
类型绑定过程或带有传递的参数的组件过程指针的参数列表被单独考虑。