Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29376 Discussions

Initialization of local variables in subroutines

Franco_B_
Beginner
1,089 Views

In Fortran 77 is it possible to globally ensure that the local variables in a subroutine are not preserved (which seems to be the default), i.e. without initializing all variables and arrays individually?

My problem is that calling a subroutine repeatedly results in different answers.
For example, if I send it an input value x, it returns the correct value y.
However, if I put it inside a loop and send it values x-1 and then x, it returns the correct output for x-1, but for x it now returns an incorrect value different to y.

0 Kudos
1 Solution
mecej4
Honored Contributor III
1,089 Views

Local variables without the SAVE attribute are not saved unless the compiler option /Qsave is used. Under these circumstances, it is the programmer's responsibility to assign values to such variables before they are used. In terms of the standard, the value of an unsaved variable is "undefined" at subprogram entry, but there is no guarantee that its value will be different from the value that it had when the same subprogram was last exited.

I find your "without initializing .. individually" rather perplexing and contradictory. If you adopt a "don't ask, don't use" policy, it should not matter what the memory contains for a variable whose value, according to the Fortran standard, is "undefined".

View solution in original post

0 Kudos
2 Replies
mecej4
Honored Contributor III
1,090 Views

Local variables without the SAVE attribute are not saved unless the compiler option /Qsave is used. Under these circumstances, it is the programmer's responsibility to assign values to such variables before they are used. In terms of the standard, the value of an unsaved variable is "undefined" at subprogram entry, but there is no guarantee that its value will be different from the value that it had when the same subprogram was last exited.

I find your "without initializing .. individually" rather perplexing and contradictory. If you adopt a "don't ask, don't use" policy, it should not matter what the memory contains for a variable whose value, according to the Fortran standard, is "undefined".

0 Kudos
Arjen_Markus
Honored Contributor II
1,089 Views

As an addition to mecej4's explanation:

Some older compilers especially on Windows used to put local variables in static memory, so that they kept their value. That is not violating the standard, it merely means that if your code implicitly relies on local variables keeping their values (that is: no SAVE attribute) it just happens to work with such compilers - but not necessarily with others! Current compilers in my experience do not do this anymore.

 

0 Kudos
Reply