7

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
gilbertohasnofb
  • 1,984
  • 16
  • 28

1 Answers1

11

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

M. S. B.
  • 28,968
  • 2
  • 46
  • 73
  • 3
    This feature is quite misleading since many languages that have optional arguments also have a way to use them (usually with initialized values). But indeed, section 12.4.1.6 of Fortran 2003 states: ***A dummy argument that is not optional shall be present. An optional dummy argument that is not present is subject to the following restrictions: (1) If it is a data object, it shall not be referenced or be defined. If it is of a type for which default initialization is specified for some component, the initialization has no effect. [...]*** –  Aug 19 '13 at 13:54