Developer Guide and Reference

ID 767251
Date 10/31/2024
Public
Document Table of Contents

Define Generic Assignment

An interface block or a GENERIC statement can be used to define generic assignment. The only procedures allowed in the interface block are subroutines that can be referenced as defined assignments.

The initial line for such an interface block takes the following form:

INTERFACE ASSIGNMENT (=)

The subroutines within the interface block must have two nonoptional arguments, the first with intent OUT or INOUT, and the second with the INTENT(IN) and/or the VALUE attribute.

A defined assignment is treated as a reference to a subroutine. The left side of the assignment corresponds to the first dummy argument of the subroutine; the right side of the assignment, enclosed in parentheses, corresponds to the second argument. A defined assignment procedure with an ALLOCATABLE or POINTER dummy argument cannot be directly invoked through defined assignment; the right-hand side of the assignment operator becomes an expression, and an expression cannot have the ALLOCATABLE, POINTER, or TARGET attribute.

The ASSIGNMENT keyword extends or redefines an assignment operation if both sides of the equal sign are of the same derived type.

Defined elemental assignment is indicated by specifying ELEMENTAL in the SUBROUTINE statement.

Any procedure reference involving generic assignment must be resolvable to one specific procedure; it must be unambiguous. For more information, see Unambiguous Generic Procedure References.

The following is an example of a procedure interface block defining assignment:

  INTERFACE ASSIGNMENT (=)
    SUBROUTINE BIT_TO_NUMERIC (NUM, BIT)
      INTEGER, INTENT(OUT) :: NUM
      LOGICAL, INTENT(IN)  :: BIT(:)
    END SUBROUTINE BIT_TO_NUMERIC

    SUBROUTINE CHAR_TO_STRING (STR, CHAR)
      USE STRING_MODULE                    ! Contains definition of type STRING
      TYPE(STRING), INTENT(OUT) :: STR     ! A variable-length string
      CHARACTER(*), INTENT(IN)  :: CHAR
    END SUBROUTINE  CHAR_TO_STRING
  END  INTERFACE

The following example shows two equivalent ways to reference subroutine BIT_TO_NUMERIC:

  CALL BIT_TO_NUMERIC(X, (NUM(I:J)))
  X = NUM(I:J)

The following example shows two equivalent ways to reference subroutine CHAR_TO_STRING:

  CALL CHAR_TO_STRING(CH, '432C')
  CH = '432C'

The following generic statement adds subroutine STRING_TO_CHAR to the defined assignment operator. There must be an accessible explicit interface for STRING_TO_CHAR.

  GENERIC :: ASSIGNMENT (=) => STRING_TO_CHAR