does not have the concept of a variable
with global scope
, like C
does. If there is a variable used by many subroutine
s, it may be inconvenient to pass the variable every time in the parameter list of the function
call. An example of this would be constants that are defined at run time, perhaps read from a command line or parameter file, used in calculations in every subroutine. To facilitate this, FORTRAN allows named sets of variables to be declared as COMMON. A program can have many COMMON blocks, and each COMMON block can have many variables, each of which can be of a different type. FORTRAN looks at the position in the COMMON block of each variable, not its name, so it is possible to access the same block but rename its variables in each different subroutine. This is particularly useful, because when a subroutine uses a COMMON block, it uses the whole block, and this may result in a variable being redeclared. This feature should be used sparingly, as it can make code difficult to maintain (like overuse of #define
in C or operator overloading
can). Names of COMMON blocks must be unique, and variable names within a COMMON block must be unique, but the same variable name could occur in multiple COMMON blocks.
Accessing a COMMON block by name moves the variables in that block into the scope of the subroutine. In some ways, this is more elegant than C's global variables, because it adds the advantage of namespacing. COMMON functionality can be emulated in Java using static classes containing static variables, one class being equivalent to one COMMON block.
The syntax of a COMMON block is:
COMMON / com1 / var1, var2
This declares two variables, an integer called var1 and a real number called var2 (if you do not explicitly set a type, FORTRAN assumes variables with named beginning with letters from I to N are integer, others are floating point) and a COMMON block called com1. Any subroutine which contains an identical COMMON statement to this one, will have access to a variable called var1 with a value of 10. If the subroutine changes this value, it will change globally, and any subroutine using the common block will see the new value.