Fortran for C/C++ Programmers: Part I

Due to my current occupation, which involves numerical computations, I have to deal with Fortran in its different flavors. Since in the past I have almost exclusively programmed C/C++ and never had used Fortan I ran into some nasty bugs, which I want to share, guessing that there are probably more people in the same situation. Most of these bugs are simply because of the fact, that one projects the known C-semantics onto Fortran. Or saying it differently: the bug sits between the keyboard and the chair :)

In this first post I want to start with the following example

subroutine bar()
 
implicit none
 
logical :: foo = .false.
! do other stuff
end subroutine

which is compared to:

subroutine bar()
 
implicit none
 
logical :: foo
foo = .false.
! do other stuff
end subroutine

Looks basically the same. Apparently it is NOT. The problem is that for Fortran every variable which is initialized at declaration is automatically marked saved, which, just to make it clear, corresponds to the static keyword in the C world. To make it even more precise the first example is the same as:

subroutine bar()
 
implicit none
 
logical, save :: foo = .false. ! foo's value is persistent across subroutine calls
! do other stuff
end subroutine

Or the same function in C:

void bar()
{
    static bool foo = false;
    // do other stuff
}

This is just a habit thing, since in C and C++ there is not a problem with initialization at declaration. When I experienced the bug above I luckily had a simple function and a unit test which helped to reveal the bug quite fast. Otherwise one probably could keep staring at code for some time, falsely assuming this part of the code being too simple to fail.