HP Fortran Programmer's Reference (September 2007)

Program units and procedures
Arguments
Chapter 7176
As an example of how to use the keyword option, consider the SUM intrinsic function. As
described in “SUM(ARRAY, DIM, MASK)” on page 628, this intrinsic has three arguments:
array, dim, and mask, in that order; dim and mask are optional arguments. The following are
therefore valid references to SUM:
SUM(a,2)
SUM(a,mask=a.gt.0)
SUM(dim=2,array=a)
The following is an invalid reference—the mask keyword must be specified:
SUM(a,dim=2,a.gt.0) ! ILLEGAL, mask keyword missing
Optional arguments
An actual argument may be omitted from the argument list of a procedure reference if its
corresponding dummy argument is optional. A dummy argument is optional if it is declared
with the OPTIONAL attribute and appears at the end of the argument list. The procedure
reference may also omit trailing arguments with the OPTIONAL attribute. Otherwise,
keywords must be provided to maintain an identifiable correspondence (see “Keyword option”
on page 175). Only procedures with an explicit interface may have optional arguments.
The following example, optional_arg.f90, references an internal function that declares one of
its dummy arguments with the OPTIONAL attribute. (Internal functions have an explicit
interface, making them eligible for optional arguments; see “Internal procedures” on
page 167.) The function uses the PRESENT intrinsic to test whether or not the optional
argument is present. If the intrinsic returns .TRUE. (an actual argument is associated with
the optional dummy argument), the function returns the sum of the two arguments;
otherwise, it returns the required argument incremented by 1.
Example 7-5 optional_arg.f90
PROGRAM main
! illustrates the optional argument feature
INTEGER :: arg1 = 10, arg2 = 20
PRINT *, add_or_inc(arg1) ! omit optional argument
PRINT *, add_or_inc(arg1, arg2)
CONTAINS ! internal procedure with explicit interface
INTEGER FUNCTION add_or_inc(i1, i2)
! return the sum of both arguments if the second argument
! (declared as optional) is present; otherwise, return the
! first argument incremented by 1
INTEGER :: i1
INTEGER, OPTIONAL :: i2 ! optional argument