If I initialize a variable in a Fortran declaration statement, that variable implicitly receives a SAVE attribute and the initialization expression will only be executed once.
For example, the following program
program test
implicit none
call foo()
call foo()
contains
subroutine foo ()
integer :: i = 0
i = i + 1
write(*,*) i
end subroutine foo
end program test
will print
1
2
Since this is different in many other languages I was wondering why the Fortran standard committee chose this behavior?
Thanks a lot! Mike
The SAVE statement preserves items in a subprogram after the RETURN or END statements are executed, preventing them from becoming undefined.
A Fortran function is similar to a mathematical function, which takes one or many parameters as inputs and returns a single output value. A Fortran subroutine is a block of code that performs some operation on the input variables, and as a result of calling the subroutine, the input variables are modified.
The purpose of a function is to take in a number of values or arguments, do some calculations with those arguments and then return a single result. There are some functions which are written into FORTRAN and can be used without any special effort by you, the programmer. They are called intrinsic functions.
A DATA statement is a nonexecutable statement, and must appear after all specification statements, but it can be interspersed with statement functions and executable statements, although this is non-standard @ . Note -
This is mainly due to historical reasons. Old compilers (Fortran IV(66) and before) were implemented to produce programs using mainly static memory. Old machines even didn't have any stack. Therefore the programs behave, as the variables were defined as save
.
The predecessor of the variable initialization, the DATA
statement, is more like defining an initial content of static memory (similar to the directives for the data segment in assembly), than the on call variable initialization you may know from C. The syntax became similar to the C variant later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With