next up previous contents
Next: Pointers and Targets Up: Derived Types Previous: Arrays and Derived Types   Contents

Derived Types and Procedures

In F90 derived type objects can be passed as arguments in much the same manner intrinsic objects do. They can be given attributes (OPTIONAL, INTENT, dimension, SAVE, ALLOCATABLE, etc) However, some care needs to be exercised, as discussed below.

Consider the following sequence of code:

program dist 
implicit none 
real, external :: distance 
type Point 
  real :: x,y,z 
end type Point 
type(Point) ::a,b 
a = point(1.,2.,3.) 
b = point(4.,6.,8.) 
print*, distance(a,b) 
end program dist 
!
real function distance(a,b) 
type Point 
  real :: x,y,z 
end type Point 
type(Point), intent(in) :: a,b 
distance = sqrt( (a\%x-b\%x)**2 + & 
  (a%y-b%y)**2 + (a%z-b%z)**2 ) 
end function distance \\
Everything seems fine, but in reality it is not, because of the following. The type Point definition in the main program and the type Point definition in the distance function declare two different types, with two different scopes (the definitions behave the same way two different local variable declarations would behave). Recall that the compiler represents the derived types however it sees fit, and it can happen that the main program type(Point) variables have a different storage scheme than the distance function's type(Point) variables.

The solution to this ``problem'' is to make the type definition accessible by either

As a general rule, it is therefore preferable to always encapsulate type definitions in modules, and make them visible by USE association. For example, the module

module Pnt
type Point 
  reaL :: x,y,z 
end type Point 
end module Pnt
can be used in both the main program and external function.

Functions can return results of an arbitrary defined type. For example, consider the type of ``double precision complex numbers'', and the function that adds two double precision complex numbers returns a double precision complex result

module dpc 
  type DP_Complex 
   double precision :: re, im 
  end type DP_Complex 
contains 
  FUNCTION DPC_Add(a,b) 
  type(DP_Complex), intent(in) :: a,b 
  type(DP_Complex) :: DPC_Add 
   DPC_Sum%re = a%re + b%re 
   DPC_Sum%im = a%im + b%im 
  end function DPC_Add
end module dpc

next up previous contents
Next: Pointers and Targets Up: Derived Types Previous: Arrays and Derived Types   Contents
Adrian Sandu 2001-08-26