OPTIONAL

Purpose

The OPTIONAL attribute specifies that a dummy argument need not be associated with an actual argument in a reference to the procedure.

Syntax

Read syntax diagramSkip visual syntax diagram
>>-OPTIONAL--+----+--dummy_arg_name_list-----------------------><
             '-::-'                        

Rules

A procedure that has an optional dummy argument must have an explicit interface in any scope in which the procedure is referenced.

Use the PRESENT intrinsic function to determine if an actual argument has been associated with an optional dummy argument. Avoid referencing an optional dummy argument without first verifying that the dummy argument is present.

A dummy argument is considered present in a subprogram according to the rules described in the section: Restrictions on optional dummy arguments not present.

An optional dummy argument that is not present may be used as an actual argument corresponding to an optional dummy argument, which is then also considered not to be associated with an actual argument. An optional dummy argument that is not present is subject to the restrictions specified in the section: Restrictions on optional dummy arguments not present

The OPTIONAL attribute cannot be specified for dummy arguments in an interface body that specifies an explicit interface for a defined operator or defined assignment.

Table 1. Attributes compatible with the OPTIONAL attribute
ALLOCATABLE  1  EXTERNAL TARGET
ASYNCHRONOUS INTENT VALUE  1 
CONTIGUOUS  2  POINTER VOLATILE
DIMENSION    
Note:
  •  1  Fortran 2003
  •  2  Fortran 2008
Notes:
  1. Fortran 2008.

Examples

      SUBROUTINE SUB (X,Y)
        INTERFACE
          SUBROUTINE SUB2 (A,B)
            OPTIONAL :: B
          END SUBROUTINE
        END INTERFACE
        OPTIONAL :: Y
        IF (PRESENT(Y)) THEN          ! Reference to Y conditional
          X = X + Y                   ! on its presence
        ENDIF
        CALL SUB2(X,Y)
      END SUBROUTINE

      SUBROUTINE SUB2 (A,B)
        OPTIONAL :: B                 ! B and Y are argument associated,
        IF (PRESENT(B)) THEN          ! even if Y is not present, in
          B = B * A                   ! which case, B is also not present
          PRINT*, B
        ELSE
          A = A**2
          PRINT*, A
        ENDIF
      END SUBROUTINE

Related information