Can we avoid creating a local variable if an optio

2019-06-22 13:32发布

问题:

I am having a problem with the PRESENT statement with Fortran 95. Currently I am using Silverfrost's Plato and their FTN95 compiler (in "Release Win32" mode). What I wanted to do is to create a subroutine SUB(a,b), where b is an optional variable. So far so good, but the problem arises when I try to give a new value to b with if (.NOT. present(b)) b=0. This is the code:

module MOD
contains
  subroutine SUB(a,b)
  implicit none
  integer :: a
  integer,optional :: b
  if (.NOT. present(b)) b=0
  print*, a,b
  end subroutine SUB
end module MOD

program TEST
use MOD
implicit none

integer :: i=2, j=1

call SUB(i,j)
call SUB(i)
call SUB(j)

end program TEST

Is there an elegant way out of this situation, or do I really need to create another variable, b_aux for instance, and then use the following code?:

if (present(b)) then
  b_aux=b
  else
    b_aux=0
endif

回答1:

You can't use a non-existent variable, so an approach such as the auxiliary local variable is needed.