program main
some declarations
real alpha, beta
common /coeff/ alpha, beta
statements
stop
end
subroutine sub1 (some arguments)
declarations of arguments
real alpha, beta
common /coeff/ alpha, beta
statements
return
end
subroutine sub2 (some arguments)
declarations of arguments
real alpha, beta
common /coeff/ alpha, beta
statements
return
end
Here we define a common block with the name coeff.
The contents of the common block are the two variables alpha
and beta. A common block can contain as many variables as you like.
They do not need to all have the same type. Every subroutine that
wants to use any of the variables in the common block has to
declare the whole block.
Note that in this example we could easily have avoided common blocks by passing alpha and beta as parameters (arguments). A good rule is to try to avoid common blocks if possible. However, there are a few cases where there is no other solution.
common / name / list-of-variables
You should know that
subroutine sub3 (some arguments)
declarations of arguments
real a, b
common /coeff/ a, b
statements
return
end
This declaration is equivalent to the previous version that
used alpha and beta. It is recommended that
you always use the same variable names for the same common block
to avoid confusion. Here is a dreadful example:
subroutine sub4 (some arguments)
declarations of arguments
real alpha, beta
common /coeff/ beta, alpha
statements
return
end
Now alpha is the beta from the main program and vice versa.
If you see something like this, it is probably a mistake.
Such bugs are very hard to find.
program main
integer nmax
parameter (nmax=20)
integer n
real A(nmax, nmax)
common /matrix/ A, n
This common block contains first all the elements of A, then
the integer n. Now assume you want to use the
matrix A in some subroutines. Then you have to include the
same declarations in all these subroutines, e.g.
subroutine sub1 (...)
integer nmax
parameter (nmax=20)
integer n
real A(nmax, nmax)
common /matrix/ A, n
Arrays with variable dimensions cannot appear in common blocks,
thus the value of nmax has to be exactly the same as in the
main program. Recall that the size of a matrix has to be known at
compile time, hence nmax has to be defined in a parameter statement.
This example shows there is usually nothing to gain by putting arrays in common blocks. Hence the preferred method in Fortran 77 is to pass arrays as arguments to subroutines (along with the leading dimensions).