将可选参数传递给子例程 [英] Handing optional parameters to subroutines

查看:151
本文介绍了将可选参数传递给子例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个子程序.一个调用另一个,两者都具有相同的可选参数:

I have two subroutine. One calls the other and the both have the same optional parameter:

program main
    call a()
    call a(7)

contains
    subroutine a(var)
        implicit none
        integer, intent(in), optional   :: var

        call b(var)
    end subroutine

    subroutine b(var)
        implicit none
        integer, intent(in), optional   :: var

        if(present(var)) then
            write (*,*) "var =  ", var
        else
            write (*,*) "not given"
        endif
    end subroutine
end program main

在第一次调用a时,将var赋予b,即使未给出.我在gfortran和ifort中尝试了这一点,它似乎起作用了.我想知道的是:

In the first call of a gives var to b even though it is not given. I tried this in gfortran and ifort and it seems to work. I am wondering though:

这是有效的standard-fortran还是我在这里滥用一些漏洞?

Is this valid standard-fortran or am I just abusing some loophole here?

推荐答案

我们使用了很多次,但是您的问题使我也进行了验证.

We use that many times, but your question lead to me to also verify it.

根据《现代Fortran解释》(第5.13章)中的Metcalf,Reid和Cohen,它是有效的代码.可选参数可以通过任意数量的后续调用传播,只要哑元参数也是可选的即可.

According to Metcalf, Reid, and Cohen in Modern Fortran Explained (ch. 5.13), it is valid code. Optional arguments can be propagated through any number of subsequent calls as long as the dummy arguments are also optional.

Fortran标准对此也有一些评论(第15.5.2.12章):

Also the Fortran standard has some comments on this (ch. 15.5.2.12):

不存在的可选虚拟参数受以下限制.

An optional dummy argument that is not present is subject to the following restrictions.

..

  1. 不得作为与非可选虚拟参数相对应的实际参数提供 除了作为内在函数PRESENT的自变量或作为函数的自变量之外 引用是一个常量表达式.
  1. shall not be supplied as an actual argument corresponding to a nonoptional dummy argument other than as the argument of the intrinsic function PRESENT or as an argument of a function reference that is a constant expression.

..

除了上面的列表中指出的以外,它可以作为与可选虚拟对象相对应的实际参数提供 论点,然后也将其视为不存在.

Except as noted in the list above, it may be supplied as an actual argument corresponding to an optional dummy argument, which is then also considered not to be present.

这篇关于将可选参数传递给子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆