Home
Fortran Resources
Pitfalls
Fortran Manifesto
CVS Primer
My Codes
Personal

AddThis Button
Hit Counter
Table of Contents
Warning This site is currently under construction.

1. Pitfalls

1.1. Initializing Local variables

Warning

Do note initialize local variables in procedures! In Fortran this implicitly gives the variable the SAVE attribute, causing it to retain its value upon exiting the procedure, and then initialize to its old value upon re-entering the procedure. If this behaviour is desired the variable should be explicitly given the SAVE attribute to prevent confusion. In Example 1 the variable int has (probably inadvertently) acquired the SAVE attribute. Example 2 accomplishes the same thing as Example one but it is much clearer, and stylistically preferred. Example 3 is probably what the author of Example 1 was trying to accomplish. Out of all the examples this is the only procedure which will run more than once. In examples 1 and 2 int will retain the a value of SIZE(in,1) and after the first execution the do loop will exit before one cycle.

1
SUBROUTINE example(in,out)
REAL, DIMENSION(:,:), INTENT(in)  :: in
REAL, DIMENSION(:),   INTENT(out) :: out
INTEGER :: int = 0 ! DON'T DO THIS!!!!!!!!!!!!!

DO
   int = int + 1
   IF (int >= SIZE(in,1)) THEN
      EXIT
   END IF

   ! ...

END DO
2
SUBROUTINE example(in,out)
REAL, DIMENSION(:,:), INTENT(in)  :: in
REAL, DIMENSION(:),   INTENT(out) :: out
INTEGER, SAVE :: int = 0 ! This is equivalent to 1 but stylistically
                         ! preferred.

DO
   int = int + 1
      IF (int >= SIZE(in,1)) THEN
      EXIT
   END IF

   ! ...

END DO
3
SUBROUTINE example(in,out)
REAL, DIMENSION(:,:), INTENT(in)  :: in
REAL, DIMENSION(:),   INTENT(out) :: out
INTEGER :: int ! This is probably what the author in 1 meant to
               ! accomplish.

int = 0

DO
   int = int + 1
      IF (int >= SIZE(in,1)) THEN
      EXIT
   END IF

   ! ...

END DO