Declarations, initialisation and SAVE
A Fortran variable is declared once, at the top of its unit, and the declaration says the type, the shape and every attribute the compiler needs to check its uses. This lesson goes through the parts of a declaration, the initialiser that can sit inside it, and the one attribute that changes how long a value lives: SAVE.
Declarations
A declaration names one or more variables and gives their type. The double colon separates the type and its attributes from the names, and it is required as soon as an attribute is present; a bare integer i is accepted for old code, and modern style never writes it.
The file declare.f90:
program declare
implicit none
integer :: count = 0
real :: factor = 2.5
character(len=8) :: name = "Fortran"
logical :: ready = .true.
count = count + 1
print *, "count :", count
print *, "factor:", factor
print *, "name :", name
print *, "ready :", ready
end program declare
gfortran -Wall -Wextra -std=f2018 declare.f90 -o declare
./declare
count : 1
factor: 2.50000000
name :Fortran
ready : T
The character variable is declared with a length of 8 and initialised with 7 characters, so the value is padded with a blank on the right and prints as Fortran followed by a space. That padding is a property of the variable, not of the print statement: every character value in Fortran has a fixed length, and a shorter string stored in it is padded.
The parts of a declaration
A declaration has four parts, and each of them can be left out except the type and the name:
- The type: integer, real, complex, logical, character, or a derived type from the lesson on derived types.
- The kind and length in parentheses: real(real64), character(len=32). A type without them takes the default, which is 4 bytes for a real and one character for a character.
- The attributes after a comma: parameter, intent(in), allocatable, dimension(3), pointer, save, public.
- The names, one or more, separated by commas, each with optional bounds and an optional initialiser.
One declaration may name several variables of the same type and attributes: integer :: i, j, k. Write one per line when their meanings differ, because the attribution of a comment and the attribution of a type should not be two different guesses.
Initialisation in the declaration
The = in a declaration is not an assignment. It is part of the declaration, and the value is stored before the program starts, once. Two consequences follow, and both surprise a reader coming from a language where a local variable is created on every call:
- The value survives between calls, because the variable itself survives. A declaration initialiser gives the variable the SAVE attribute whether or not the word is written.
- The initialiser must be a constant expression. integer :: n = 3 is fine; integer :: n = 2 * m is not, when m is a variable.
A variable that is only meant to start at a value should be assigned that value in the executable part instead, which is what the program above does with count: the declaration sets it to zero once, and the assignment makes the intent visible.
SAVE and the value that survives
A function that counts its own calls is the smallest program that shows the difference. The counter is declared with save and an initialiser, and it keeps its value from one call to the next.
The file saved.f90:
module ids
implicit none
contains
integer function next_id() result(id)
integer, save :: last = 0
last = last + 1
id = last
end function next_id
end module ids
program saved
use ids, only: next_id
implicit none
integer :: i
do i = 1, 3
print *, "call", i, "returns", next_id()
end do
end program saved
gfortran -Wall -Wextra -std=f2018 saved.f90 -o saved
./saved
call 1 returns 1
call 2 returns 2
call 3 returns 3
Delete save and the initialiser and the same function reads a variable that was never set. The compiler says so, because it can see the read and the declaration in one place:
The file plain_mod.f90:
module plain_ids
implicit none
contains
! No initialiser, no SAVE: the value is undefined on every entry.
integer function next_plain() result(id)
integer :: last
last = last + 1
id = last
end function next_plain
end module plain_ids
gfortran -Wall -Wextra -std=f2018 -c plain_mod.f90
plain_mod.f90:9:19:
9 | last = last + 1
| ^
Warning: 'last' is used uninitialized [-Wuninitialized]
plain_mod.f90:8:16:
8 | integer :: last
| ^~~~
note: 'last' was declared here
A module has one more consequence for a saved value: the variable belongs to the module, so it exists once for the whole program and every unit that uses the module shares it. That makes a module variable the normal way to keep state, and a saved local the exception for a procedure that must keep something private.
Threads break the picture. Two threads calling a saved counter share it and can update it at the same moment, so a saved variable that is written after the program has started needs a lock, or a design without it. The lesson on OpenMP returns to this.
Where declarations go
A program unit has a specification part and an executable part, in that order. Every declaration, use, implicit none, interface and parameter belongs to the first; every assignment, loop and print to the second. The contains section comes after the executable part.
A declaration in the middle of the executable part is an error, and the message says which statement the compiler expected instead. That rule is why a Fortran procedure reads top-down: all the facts about the data come first, then the work that uses them.
Exercises
- Declare three integers in one statement and give each a different initial value. Does it build?
- Change character(len=8) to character(len=3) in the first program. What does the name print now, and why?
- Call next_id five times instead of three. What does the fifth call return?
- Remove save but keep the initialiser. Does the counter still work?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
::separate in a declaration?Answer
The type and attributes from the names
The double colon comes before the list of names and is required once an attribute is present.
-
When is a declaration initialiser applied?
Answer
Once, before the program starts
The value is part of the declaration, so it is set in the static storage of the variable.
-
What attribute does an initialiser in a declaration imply?
Answer
SAVE
A variable with an initialiser keeps its value between calls, which is exactly SAVE.
-
What does a saved local variable in a module keep between calls?
Answer
Its value, because the variable itself lives for the whole program
SAVE gives the variable static storage duration.
-
What does the compiler warn about a local that is read before it is set?
Answer
Warning: 'last' is used uninitialized [-Wuninitialized]
The warning names the variable and the read, and a note points at the declaration.
-
Where do the declarations of a program unit go?
Answer
In the specification part, before the first executable statement
Fortran has one specification part per unit, and it comes first.
-
What does this program print?
program p implicit none integer :: n = 2 n = n + 1 print *, n end program pAnswer
3
The declaration sets n to 2 once, and the assignment makes it 3.
-
What does
character(len=8) :: name = "Fortran"hold?Answer
Seven characters and one blank
The declared length is 8 and the shorter value is padded with blanks.
-
Which initialiser is legal in a declaration?
Answer
integer :: n = 2 * 3
The initialiser must be a constant expression, so it may not read a variable or call a function.
-
Why is a saved counter unsafe with threads?
Answer
Two threads share it and can update it at the same moment
One variable and two writers: the increments can overwrite each other.
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