“Saving” a common block

2020-03-19 06:51发布

问题:

I'm dealing with some legacy code that uses COMMON blocks extensively and sometimes uses the SAVE statement. After consulting the Fortran standard, it says:

The appearance of a common block name preceded and followed by a slash in a SAVE statement has the effect of specifying all of the entities in that common block.

Under what circumstances does placing a variable in a common block not imply SAVE? Since the variable must be accessible in any other program unit that includes that common block, how could it not be SAVEed?

回答1:

I had to look it up, because I was under the same impression as you are.

It seems that only variables in an unnamed, so-called blank, common block retain their definition status across the entire program. Unsaved variables in a named common block become undefined on return from a subprogram, unless another currently active program unit includes a common statement for the same common block.

From the standard (Fortran 77, but the latest one contains similar wording):

17.3 Events That Cause Entities to Become Undefined
[...]
6. The execution of a RETURN statement or an END statement within a subprogram causes all entities within the subprogram to become undefined except for the following:
[...]
d. Entities in a named common block that appears in the subprogram and appears in at least one other program unit that is either directly or indirectly referencing the subprogram



回答2:

Many compilers of the Fortran 77 era "saved" all local procedure variables, whether or not "SAVE" was specified. This is a common reason for legacy programs to fail with modern compilers, which will undefine variables when they go out of scope, as allowed by the language standard. Probably those older compilers would also maintain the values of all common variables for the duration of the program run, even though that wasn't required by the language standard.