Derived Types and Allocatable
Derived Type
Grouped Fields
A type definition groups named fields. The auto-generated structure constructor builds an instance.
Program
Play the program to build a rectangle and compute its area from fields.
derived_type.f90
Replay: real traced execution (multi-file project)
program derived_type_demo
implicit none
type :: rectangle
integer :: width
integer :: height
end type rectangle
type(rectangle) :: rect
integer :: area_val
rect = rectangle(4, 3)
area_val = rect%width * rect%height
print '(I0)', area_val
end program derived_type_demo
rect ← rectangle(width=4, height=3)
8integer :: area_val9rect = rectangle(4, 3)10area_val = rect%width * rect%heightvalues this steprectangle(width=4, height=3)rectarea_val ← 12
9rect = rectangle(4, 3)10area_val = rect%width * rect%height11print '(I0)', area_valvalues this step12area_val4rect%width3rect%heightprint '(I0)', area_val
10 area_val = rect%width * rect%height11 print '(I0)', area_val12end program derived_type_demooutput12values this step12area_val
Follow the Rectangle
type rectanglegroupswidthandheight.rect = rectangle(4, 3)stores width4and height3.rect%widthreads4.rect%heightreads3.area_val = 4 * 3becomes12, and the program prints12. | field | value | | --- | --- | |rect%width| 4 | |rect%height| 3 | |area_val| 12 |
type
`type :: rectangle ... end type` defines a record.
constructor
`rectangle(4, 3)` builds an instance positionally.
% access
`rect%width` reads one field.
Exercise: derived_type.f90
Reproduce the printed value 12, then change width or height and predict the new area before running it.