0

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?

Stein
  • 3,179
  • 5
  • 27
  • 51

1 Answers1

0

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.

PVitt
  • 11,500
  • 5
  • 51
  • 85