Purpose of SAVE and COMMON together in Fortran

1.8k views Asked by At

Does a common block in Fortran serve the purpose of global variables?

If this is the case, then can these values be modified by a subroutine?

Will SAVE store the modified parameters from within a subroutine for uses other than from inside the subroutine?

2

There are 2 answers

1
francescalus On

[Edit: I'm basing the answer on understanding that the question is about SAVE on a common block, not on local variables (ie., as an alternative for COMMON). Otherwise see cup's comment.]

Common blocks were indeed the approach for "global" variables in Fortran 77. The variables within the block can be modified in a subroutine and the changes will be visible elsewhere (see caveat).

SAVE doesn't directly change the ability of other subprograms to use the modified variables. Instead its purpose is to ensure that data in the block don't become undefined when the block goes out of scope. Note that if SAVE is present in one subprogram it must be present on the block in all subprograms where the block features (but not necessarily the main program).

From memory this means that (this isn't really F77; for the concept):

  call s1
  call s2
end

subroutine s1
  common /bl/ i,j
  i=2
end subroutine s1

subroutine s2
  common /b1/ i,j
  print *, i
end subroutine s2

won't be well-behaved. [Whether real-world compilers make you pay is debatable.]

Variables in a common block cannot have the SAVE attribute applied separately, and having the attribute on a local variable doesn't change its accessibility. So, for example, a SAVE K in one subroutine wouldn't make that variable accessible anywhere else. What will happen, however, is that it retains its value after control returns from there (for the next time the subroutine is entered).

Finally, there are better approaches after Fortran 77.

0
M. S. B. On

Yes, common creates global variables. Fortran >=90 provides module variables for that purpose -- module variables should be used in new code in preference to common. common adds the generally unnecessary complexity of storage order. common or module variables can be used by multiple procedures subroutines & functions) and the main program.

save is primarily for local variables in procedures, to cause those variables to retain their values across invocations. fortran SAVE statement

save can also be applied to module variables, to guarantee that they don't lose their values if no routine that uses the module is in scope. This is no longer necessary in Fortran 2008 -- see When does a module go out of scope in Fortran 90/95?