Fortran 2003 / 2008: Elegant default arguments?
<p>In fortran, we can define default arguments. However, if an optional argument is not present, it can also not be set. When using arguments as keyword arguments with default values, this leads to awkward constructs like </p>

<pre><code>PROGRAM PDEFAULT 

  CALL SUB
  CALL SUB(3)

CONTAINS 
  SUBROUTINE SUB(VAL)
    INTEGER, OPTIONAL :: VAL
    INTEGER :: AVAL ! short for "actual val"

    IF(PRESENT(VAL)) THEN
       AVAL = VAL
    ELSE 
       AVAL = -1   ! default value 
    END IF

    WRITE(*,'("AVAL is ", I0)') AVAL
  END SUBROUTINE SUB

END PROGRAM PDEFAULT
</code></pre>

<p>Personally, I often ran into the problem of accidentially typing <code>VAL</code> instead of <code>AVAL</code>, i.e. the disconnect between the variable name in the interface, and the initialized value used in the code can introduce runtime bugs – let alone that this manner of initialization is rather verbose. </p>

<p>Is there some more elegant way of using optional arguments with a default value?</p>

<p><strong>Example</strong> It would feel more natural to write something like </p>

<pre><code>IF(NOT(PRESENT(VAL))) VAL = -1 
</code></pre>

<p>because it avoids the <code>VAL</code> vs <code>AVAL</code> confusion. But it isn't valid, presumably because Fortran passes arguments by reference and thus if <code>VAL</code> is not present in the <code>CALL</code> statement, no memory is associated with <code>VAL</code> and <code>VAL = -1</code> would cause a segfault. </p>