Does Fortran preserve the value of internal variables through function and subroutine calls?

前端 未结 3 788
醉酒成梦
醉酒成梦 2020-12-01 19:33

After much painful debugging, I believe I\'ve found a unique property of Fortran that I\'d like to verify here at stackoverflow.

What I\'ve been noticing is that, at

3条回答
  •  感情败类
    2020-12-01 19:57

    This has been discussed several times here, most recently at Fortran assignment on declaration and SAVE attribute gotcha

    You don't have to discover this behavior by experimentation, it is clearly stated in the better textbooks.

    Different languages are different and have different behaviors.

    There is a historical reason for this behavior. Many compilers for Fortran 77 and earlier preserved the values of ALL local variables across calls of procedures. Programmers weren't supposed to rely upon this behavior but many did. According to the standard, if you wanted a local variable (non-COMMON) to retain its value you needed to use "SAVE". But many programmers ignored this. In that era programs were less frequently ported to different platforms and compilers, so incorrect assumptions might never be noticed. It is common to find this problem in legacy programs -- current Fortran compilers typically provide a compiler switch to cause all variables to be saved. It would be silly for the language standard to require that all local variables retain their values. But an intermediate requirement that would rescue many programs that were careless with "SAVE" would be to require all variables initialized in their declarations to automatically have the SAVE attribute. Hence what you discovered....

提交回复
热议问题