Why derived data types?
A derived type is a data structure which is defined by the programmer:
- Equivalent to structs in C programming language (or matlab)
- Consists of other data types - including other derived types
We usually define new data type to encapsulate your data and hide its representation:
- A well structured and readable program should try to express its variables as objects
- Variables used in the same context should be grouped together - this makes the program flow
easier to understand and less probe to errors (less arguments for subroutines/functions)
- Derived data types is a feature which allows programmer to make object grouping possible
Declaration and visibility
For instance
type pgmImage
character(len=2) :: magics
character(len=255) :: createdby
integer :: nx, ny
integer :: maxValue
integer, allocatable :: image(:,:)
end type pgmImage
And to declare a variable of type pgmImage:
TYPE(pgmImage) :: img1, img2
TYPE(pgmImage), dimension(10) :: setOfImage
To initialize:
img1%magics='P2'
img1%createdby='# manually created...'
img1%n1 = 10
img1%ny=5
When declared in the same programming unit (variable declaration section) derived data types are visible to that unit only (and sub-units under CONTAINS statement)
When declared in a module unit, a derived type can be accessed outside the module through USE statement.
You can define a new data type using another data type:
TYPE matrix
integer :: nx, ny
integer, allocatable :: M(:,:)
END TYPE matrix
TYPE header_pgm
character(len=2) :: magics
character(len=255) :: createdby
END TYPE header_pgm
TYPE image_pgm
TYPE(matrix) :: data
TYPE(header_pgm) :: header
END TYPE image_pgm
Then to access it:
TYPE(image_pgm) :: img
img%header%magics='P2'
img%header%createdby='# Manually created...'
Summary
- Derived data types enables grouping of data to form logical objects
- A fortran program becomes more readable and modular with sensible use of derived data types