Arrays, defaults and allocatable components
The components of a type are not limited to scalars. A component may be a fixed-size array, which makes the type a fixed record of a given shape, or an allocatable array, which makes it a record that decides its size when it is built. This lesson takes both apart: how a default initialiser fills a component, how an allocatable component is sized in a function that returns the whole record, and what the language does with a component of the wrong shape.
An array component
real :: v(3) inside a type is an array component of three reals, laid out inside the record. s%v is then an ordinary array: sum(s%v) reduces it, s%v * 10.0 multiplies every element, s%v(2) reads one. The whole-array rules of part 4 apply to a component exactly as they apply to a variable, because a component reference is a designator like any other.
The file comp.f90:
module stats_mod
implicit none
type :: sample
character(len=8) :: name = 'sample'
real :: v(3) = 0.0
end type sample
type :: series
character(len=8) :: name = 'series'
real, allocatable :: data(:)
end type series
contains
function make_series(name, n) result(s)
character(len=*), intent(in) :: name
integer, intent(in) :: n
type(series) :: s
integer :: i
s%name = name
allocate(s%data(n))
do i = 1, n
s%data(i) = real(i) ** 2
end do
end function make_series
subroutine show_sample(s, label)
type(sample), intent(in) :: s
character(len=*), intent(in) :: label
print '(a,a,a,3f6.1,a,f7.2)', label, trim(s%name), ' v =', s%v, ' sum = ', sum(s%v)
end subroutine show_sample
end module stats_mod
program compdemo
use stats_mod
implicit none
type(sample) :: a, b
type(series) :: s, empty
call show_sample(a, 'default: ')
b = sample('three', [1.0, 2.0, 3.0])
call show_sample(b, 'given: ')
b%v = b%v * 10.0
call show_sample(b, 'scaled: ')
print '(a,f8.2)', 'mean of b%v = ', sum(b%v) / size(b%v)
print '(a,l1)', 'empty%data allocated = ', allocated(empty%data)
s = make_series('squares', 5)
print '(a,a,a,i0,a,f8.2)', trim(s%name), ': ', 'n = ', size(s%data), ' sum = ', sum(s%data)
print '(a,l1)', 's%data allocated = ', allocated(s%data)
end program compdemo
gfortran -Wall -Wextra -std=f2018 comp.f90 -o comp
./comp
default: sample v = 0.0 0.0 0.0 sum = 0.00
given: three v = 1.0 2.0 3.0 sum = 6.00
scaled: three v = 10.0 20.0 30.0 sum = 60.00
mean of b%v = 20.00
empty%data allocated = F
squares: n = 5 sum = 55.00
s%data allocated = T
The first line is a record that was declared and never assigned: its name came from the default and its array from the default, three zeros. The third line is a whole-array operation on a component, and the fourth reduces it: sum(b%v) / size(b%v) is 60 / 3. A component behaves like a variable in every expression.
Default values
real :: v(3) = 0.0 is a default initialiser with a scalar on the right: every element gets the value. An array on the right is allowed when it has the shape of the component, so real :: v(3) = [1.0, 2.0, 3.0] would work as well. The default applies to every variable of the type that is not assigned before it is read, and it also fills any component the constructor does not mention.
A default is not a constant and not a shared value: each variable of the type gets its own copy. It is also the reason a type is easier to use than it looks: a record with a sensible default can be declared and passed around before its real contents are known, and the parts nobody set are still defined values rather than whatever was in memory.
An allocatable component
real, allocatable :: data(:) is a component whose size is chosen when the record is built. The record series has one of them, and make_series allocates it with the length it was given and fills it with squares. The function returns the whole record, so the allocation made inside it arrives in the caller: allocation status and size travel with the value.
That is the modern way to write a record of variable size, and it replaces the two older ones: a fixed maximum length with an integer saying how much is used, and a pointer component that the caller has to free. An allocatable component is deallocated automatically when the record goes out of scope, and an assignment between two records allocates the target as needed, which is the deep copy of section 079.
The allocated state
allocated(s%data) asks whether the component has storage, and the last two lines of the run answer both ways: the record empty was declared and never built, so its component is not allocated (F), and the one that came back from make_series is (T).
Reading size(s%data) or an element of it before the allocation is a mistake the compiler cannot always catch: the value of an unallocated allocatable is undefined, and a program that prints it prints something that looks like a number. The question to ask first is always allocated, not size.
A component of the wrong shape
A fixed-size component has the shape it was declared with, and an assignment of another shape is refused:
module stats_mod
implicit none
type :: sample
character(len=8) :: name = 'sample'
real :: v(3) = 0.0
end type sample
end module stats_mod
program badshape
use stats_mod
implicit none
type(sample) :: b
b%v = [1.0, 2.0]
print *, sum(b%v)
end program badshape
gfortran -Wall -Wextra -std=f2018 e.f90 -o e
e.f90:14:3:
14 | b%v = [1.0, 2.0]
| 1~~
Error: Different shape for array assignment at (1) on dimension 1 (3 and 2)
The message counts the elements on both sides: three on the left, two on the right. The same rule holds for every array assignment in Fortran, and the caret under b%v is how the compiler points at the part of the statement that has the wrong shape.
A component or a parallel array
The choice between a type with an array component and an array of a type with a scalar component is a real design decision. type(sample) with v(3) is one record that holds three numbers, and an array of it is a list of records. type(point) with one real each, in an array, is three separate records with one number each.
Use the array component when the numbers belong to one entity and are always used together: a vector, a set of coefficients, a name split into fields. Use the array of records when the records are independent: a list of observations, a table of results, a list of particles. The layout in memory follows the same decision, and section 045 explains why a component that is an array of three reals is contiguous.
Exercises
- Give sample a component real :: w(3) = 1.0 and print sum(a%v * a%w) for the default record. What is the value?
- Change make_series so the data are the first n odd numbers. Which two lines change?
- Declare type(series) :: t and write t = s. Print allocated(t%data) and size(t%data). Is the storage shared?
- Assign b%v = 0.0 to the record of the error section. Why is that legal when [1.0, 2.0] is not?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is
s%vwhen v is a component declaredreal :: v(3)?Answer
An array of three reals and a designator like any other array
A component reference is a designator, so whole-array rules apply.
-
What does
real :: v(3) = 0.0do?Answer
Gives every element of the component the value zero by default
A scalar default fills the whole array component.
-
How is an allocatable component of a returned record sized?
Answer
The function allocates it before returning the record
The allocation made inside the function travels with the value.
-
What does this program print?
module m implicit none type :: t integer :: n(2) = 7 end type t end module m program p use m implicit none type(t) :: x print *, x%n(2) end program pAnswer
7
Both elements take the scalar default.
-
What should be asked before reading size(s%data) of a component that may not be allocated?
Answer
allocated(s%data)
The size of an unallocated allocatable is undefined.
-
What does gfortran report for
b%v = [1.0, 2.0]when v has three elements?Answer
Error: Different shape for array assignment (3 and 2)
A fixed shape cannot receive another shape.
-
When is a record deallocated?
Answer
Automatically when the record goes out of scope
An allocatable component is managed by the record.
-
Which design fits a list of independent observations?
Answer
An array of records with scalar components
Independent records with one value each belong in an array.
-
What happens to the allocatable component on
t = s?Answer
t gets its own storage with a copy of the values
Assignment of a record does a deep copy of allocatable components.
-
Why is an allocatable component preferred to a pointer component?
Answer
Its storage is managed with the record and cannot dangle
An allocatable owns its storage and is freed with the record.
The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev