Next: Different Variable Names
Up: COMMON Blocks
Previous: Communications

COMMON Blocks

A COMMON block is a set of global variables that can be shared among two or more program units. It is called a block because all of the variables that belong to a COMMON block are stored together in the computer's memory.

Take a look at ``common1.f'' in your examples directory (or view it directly). It consists of a main program that initializes a global array ``A'', a subroutine that replaces each element in ``A'' with its square root, and a second subroutine that prints the array. Since every program unit must manipulate the array in some way, we have chosen to make the array global through the use of a COMMON block. (In this example, we could just as easily have passed the array as a parameter.)

There are lots of ways to declare common blocks, and the text goes into the details. We will concentrate on describing a disciplined approach to COMMON blocks that you should follow.

To create a COMMON block, you must first declare all of the variables that are to go into it. Thus, all three units contain the declaration

      REAL A(5,5)

You must then create a COMMON block by giving the keyword ``COMMON'', giving a name for the block (in our case MATRIX), and then giving a list of all of the variables that are to be in the block together. (In our case, A is the only one.) This is accomplished by the COMMON declaration

      COMMON /MATRIX/ A

which, you should verify, appears in each of the three units of the program.

The COMMON block accomplishes the following: Even though the declaration for A appears in three different places, A is actually stored in only one place and then shared among the three program units. Any program unit that contains the ``MATRIX'' common block will have access to A.

There is one important restriction: the name of the COMMON block must be different than every other COMMON BLOCK or unit in the program. Try the following experiment. Change the name of the ``PRNT'' subroutine to MATRIX. What happens when you try to compile it?

Click here for the answer

You can have more than one common block (as long as each one has a different name) and you can even have one common block that is unnamed. But the basic idea is the same---it is a way to share blocks of data among multiple program units.

There are all sorts of tricky things concerning COMMON blocks that you should at least know enough about to avoid. In the rest of this lesson, we'll show you some of these tricks and explain why, as a disciplined programmer, you should avoid them.


Next: Different Variable Names
Up: COMMON Blocks
Previous: Communications

Hamlet Project
hamlet@cs.utah.edu