![]() ![]() But without the save attribute k is undefined, so the using its value is illegal.Ĭompiling the program with gfortran, I found that k retained its value anyway: i, j, k= 3 3 3Ĭompiling the program with ifort and aggressive optimization options, k lost its value: i, j, k= 3 3 3 Local variable k of the subroutine is intentionally misused - in this program it is initialized in the first call since control is TRUE, but on the second call control is FALSE, so k is not redefined. LATER EDIT: update with a code example that shows incorrect usage of a local variable that should have the save attribute but doesn't: module subs ![]() Many compilers have an option to use the non-standard behavior and "save" all local variables. Some old programs were written relying on this non-standard behavior - these programs will fail on the newer compilers. This is different from the behavior of many FORTRAN 77 compilers, some of which retained the values of all local variables, even though this wasn't required by the language standard. So if you attempt to use "var" on an later call before redefining it in that call, the value is undefined and probably won't be the value calculated on a previous invocation of the procedure. In contrast to the module case, with modern compilers, without the save attribute or initialization-on-a-declaration, it is normal for local variables of procedures to lose their values across invocations. Though actually in Fortran >=90 one can omit the "save" because the initialization in the declaration implies "save". In this code fragment, "counter" will report the number of invocations of subroutine x. "save" is also important in procedures, to store "state" across invocations of the subroutine or function (as written by - "first invocation" initializations, counters, etc. But many compilers don't do this for module variables - the variables probably retain their values - it isn't worth the effort for the compiler to figure out whether a module remains in scope or not and probably module variables are treated as global variables - but don't rely on that! To be safe, either use "save" or "use" the module from the main program so that it never goes out of scope. "Undefined" means that you are not allowed to rely on the variable having the previous value if you again use the module - it might have the previous value when you re-access the module, or it might not - there is no guarantee. In principal when a module goes out-of-scope, the variables of that module become undefined - unless they are declared with the SAVE attribute, or a SAVE statement is used. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |