Handing optional parameters to subroutines [duplicate]

依然范特西╮ 提交于 2019-12-13 04:23:08

问题


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

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:

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


回答1:


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

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.

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. 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.



来源:https://stackoverflow.com/questions/51785556/handing-optional-parameters-to-subroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!