Fortran
Initialize project with meson
meson init --language=fortran --name=hello --version=0.1
Program units
main program
A program in fortran is defined with program <name>
directive and ends with end program <name>
. E.g.:
program hello
implicit none
! ...
end program hello
The name of the program is not neccisarily needed, but it is helpful when working on different programs and with organization
program foo
implicit none
integer :: a, b, n
real :: x
n = 1, 10
do n = 1, 10
call add(a, n)
end do
end program foo
function
Subprogram invoked from expressions and always returns a single result. These are side effect free. Can declare data and execute code, but are only invoked from expressions.
function sum(a, b)
integer, intent(in) :: a, b
integer :: sum
sum = a + b
end function sum
subroutine
Subprogram that can modify multiple arguments in place, but can’t be used in expressions. These can return any number of output arguments. Invoked with call
statement, e.g. call add(a, 3)
. These are better suited for work that modifies the program state, or has other side effects such as input or output
subroutine add(a, b)
integer, intent(in out) :: a
integer, intent(in) :: b
a = a + b
print *, 'a = ', a
end subroutine add
module
Nonexecutable collection of variable, function, and subroutine definitions
submodule
Extends an existing module and is used for definining variable and procedure definitions that only that module can access. Useful for more complex apps and libraries.
Variables
Fortrans typing is a static, manifest, strong system:
- static every variable has a data type at compile time, and that type remains the same throughout the life of the program
- manifest All variables must be explicitly declared in the declaration section before their use.
- strong vars must be type compatible when passed between a program and functions/subroutines.
Always use implicit none
Historically, fortran supports allowing variables to be inferred by the compiler based on the first letter of the variable. Any variable that began with I, J, K, L, M, or N was an integer and was a float otherwise. Fortran 90 was the first release which allowd completely disabling implicit typing with the implicit none
statement before declaring variables.
implicit none
will instruct the compiler to report an error if a variable is used which hasn’t been declared.