Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 39 ยท Derived Types and Pointers

Derived Types in Fortran

Group related data with Fortran derived types: define types, build constructors, access components with %, use default values, nest types and keep arrays of structures.

Scalars and arrays are not enough once your data has structure: a particle has a position, a velocity and a mass; a student has a name, an id and grades. A derived type is Fortran's record or struct. You define a new type from components, create variables of it, and pass whole records around as one unit.

Defining a type

FORTRAN
module particles
  implicit none

  type :: particle
    character(len=16) :: name = "unnamed"
    real :: mass = 1.0
    real :: pos(3) = 0.0
    real :: vel(3) = 0.0
  end type particle

end module particles

The components can be of any type, including arrays and other derived types. Defaults (= 1.0) apply whenever you declare a variable without values. Put type definitions in a module so every program unit sees the same definition.

Creating and using variables

FORTRAN
program demo
  use particles
  implicit none

  type(particle) :: p, q

  p = particle("electron", 9.109e-31, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0])
  q%name = "proton"
  q%mass = 1.673e-27

  print *, trim(p%name), p%vel(1)
  print *, trim(q%name), q%mass
end program demo

particle(...) is the structure constructor: components are given in declaration order, or by keyword (particle(name="x", mass=2.0)). Keyword form lets you leave out components that have defaults. The % operator selects a component, and you can chain it: p%pos(2).

Assigning one variable of the type to another copies every component:

FORTRAN
q = p     ! q now has p's name, mass, position and velocity
Python Stand-in: a record with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Arrays of derived types

Real programs hold many records:

FORTRAN
type(particle) :: swarm(100)
integer :: i

do i = 1, size(swarm)
  swarm(i)%mass = 1.0 + 0.01 * i
end do

print *, sum(swarm%mass)   ! array of components: all 100 masses

swarm%mass is an array section: the mass component of every element. That lets whole-array intrinsics work across records. This layout is called array of structures (AoS). When you process one component over millions of elements, structure of arrays (a type containing arrays such as real :: x(n)) can be faster because the data sits contiguous in memory. Choose by access pattern.

Nested types

FORTRAN
type :: vec3
  real :: x = 0.0, y = 0.0, z = 0.0
end type vec3

type :: body
  type(vec3) :: position, velocity
  real :: mass = 1.0
end type body

type(body) :: earth
earth%position%x = 1.496e11

Chain the % selectors. Because vec3 is a type of its own, you can attach operations to it (see interfaces and generic procedures) and, in the next lessons, procedures and pointers.

Anatomy of a derived type

type :: name Components and defaults
Constructor name(values) builds one
% selector p%mass, p%pos(2)

Define the type in a module

1 / 2

Controlling access to components

Inside a module you can hide the internals of a type:

FORTRAN
type :: account
  private
  real :: balance = 0.0
contains
  procedure :: deposit
  procedure :: get_balance
end type account

With private components, code outside the module cannot say acct%balance; it must use procedures. You can also mark individual components private or public. Hidden components are the first step toward object-oriented design in the type-bound procedures lesson.

Parameterized derived types, briefly

A derived type can take kind and length parameters, for example a matrix type whose element kind is chosen when you declare it:

FORTRAN
type :: matrix(k, n)
  integer, kind :: k = 8
  integer, len  :: n = 3
  real(k) :: a(n, n)
end type matrix

Compiler support is uneven, so use these only when you know your toolchain handles them.

Sequence and interoperable types

Components of an ordinary derived type may be laid out however the compiler likes. sequence forces declaration order, and bind(c) gives the C layout (see C interoperability). You need these only when sharing memory with other code or old common blocks.

Printing and comparing

print *, p is legal and prints all components in order (list-directed). Format control needs an explicit format that matches the components (see formatted output). The == operator is not defined for derived types by default; compare components yourself or overload operator(==).

Python Stand-in: array of records and component sums

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Defining the same type in two places; the compiler treats them as different types. Use one module.
  • Forgetting component order in a positional constructor.
  • Assuming == works on derived types.
  • Writing p.mass instead of p%mass. The dot is not the selector in Fortran.
  • Defaults on allocatable or pointer components: those get no values by default (see pointers and targets).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which operator selects a component of a derived type?

    Fortran uses the percent sign: p%mass. The dot is used only in operators such as .and.
  2. 2. Where should you define a type that several program units share?

    A module gives every unit the identical definition, avoiding mismatched duplicates.
  3. 3. What does swarm%mass evaluate to when swarm is an array of 100 particles?

    Selecting a component from an array of records gives an array section, so sum(swarm%mass) works.
  4. 4. What is a structure constructor?

    particle(...) builds a value of the type from component values.

Summary

  • A type groups components; define it once in a module.
  • Create values with structure constructors, select components with %.
  • Components may have default values, and types may nest.
  • Arrays of types and swarm%mass sections combine records with array intrinsics.
  • private components hide implementation details.

Next: Pointers and targets