Fortran Wiki
transfer

Description

Interprets the bitwise representation of source in memory as if it is the representation of a variable or array of the same type and type parameters as mold.

This is approximately equivalent to the C concept of casting one type to another.

Standard

Fortran 90 and later

Class

Transformational function

Syntax

result = transfer(source, mold[, size])

Arguments

  • source - Shall be a scalar or an array of any type.
  • mold - Shall be a scalar or an array of any type.
  • size - (Optional) shall be a scalar of type integer.

Return value

The result has the same type as mold, with the bit level representation of source. If size is present, the result is a one-dimensional array of length size. If size is absent but mold is an array (of any size or shape), the result is a one- dimensional array of the minimum length needed to contain the entirety of the bitwise representation of source. If size is absent and mold is a scalar, the result is a scalar.

If the bitwise representation of the result is longer than that of source, then the leading bits of the result correspond to those of source and any trailing bits are filled arbitrarily.

When the resulting bit representation does not correspond to a valid representation of a variable of the same type as mold, the results are undefined, and subsequent operations on the result cannot be guaranteed to produce sensible behavior. For example, it is possible to create logical variables for which var and .not. var both appear to be true.

Example

program test_transfer
  integer :: x = 2143289344
  print *, transfer(x, 1.0)    ! prints "nan" on i686
end program

Comments

Joe Krahn: Fortran uses molding rather than casting.

Casting, as in C, is an in-place reinterpretation. A cast is a device that is built around an object to change it’s shape.

Fortran TRANSFER reinterprets data out-of-place. It can be considered molding rather than casting. A mold is a device that confers a shape onto an object placed into it.

The advantage of molding is that data is always valid in the context of the variable that holds it. For many cases, a decent compiler should optimize TRANSFER into a simple assignment.

There are disadvantages of this approach. It is problematic to define a union of data types because you must know the largest data object, which can vary by compiler or compile options. In many cases, an EQUIVALENCE would be far more effective, but Fortran Standards committees seem oblivious to the benefits of EQUIVALENCEs when used sparingly.

category: intrinsics