next up previous contents
Next: EQUIVALENCE statements Up: Introduction to FORTRAN Previous: CHARACTER Constants as Arguments

   
COMMON statements

The COMMON statement allows the user to define a section of memory independent of any routine and to assign variable and array names to it. For example:-
COMMON/STATUS/ARRAY(2,7),ICOUNT,ENERGY
defines a section of memory to contain an array followed by two variables and gives the section the name STATUS. Any number of sections, each of which is called a COMMON BLOCK, may be may be accessed by any routine delcaring them. Shown below is a simple example of two routines communicating via a common block:-

 
        COMMON/COMM/ ICOUNT
 
        ICOUNT=1
        CALL INCR
        PRINT *,'ICOUN = ',ICOUNT
 
        STOP
        END
 
        SUBROUTINE INCR
 
        COMMON/COMM/ ICOUNT
 
        ICOUNT=ICOUNT+1
 
        RETURN
        END
If this program is run, it produces the output:-
ICOUNT = 2

The COMMON statement defines a specific section of memory but the names used in the statement are local to the routine in which the statement appears. The order in which the names appear determine their position relative to the start of the section. This means that the routine INCR could have been coded:-

 
        SUBROUTINE INCR
 
        COMMON/COMM/ ISUM
 
        ISUM=ISUM+1
 
        RETURN
        END

without affecting the result from the program. This is however VERY BAD PRACTICE. Unless there are very good reasons, always use the same COMMON statement in all routines that require it for otherwise trying to understand the program becomes more difficult. A common block may contain arrays and variables of any data type with the one restriction that character must not be mixed with other types. So the following group of statements might define two common blocks :-

 
        COMMON/BLK1/ ICOUNT,SUMS(6),TEST
        COMMON/BLK2/ STRING,TABLES(10)
        LOGICAL  TEST
        CHARACTER*3  STRING
        CHARACTER*5  TABLES
Variables and arrays in common blocks can be used exactly as if they were local to the routine. One word of warning about the use of common blocks. They are very useful but if used unnecessarily can make a program obscure. A program that has many routines all accessing and modifying the same common can be difficult to understand. Try to organise your data into logical groups and use separate commons. Then keep the access to each common, particularly those that modify values, to a minimum.
Exercise 17

Rewrite the subroutine CROSS from exercise 15 but this time without arguments and using the common:-

COMMON/CRSCOM/ A(3),B(3),C(3)
* * *


next up previous contents
Next: EQUIVALENCE statements Up: Introduction to FORTRAN Previous: CHARACTER Constants as Arguments
n west (APC)
2000-03-08