Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Check for duplicated variables in local subroutines

Status
Not open for further replies.

GerritGroot

Technical User
Nov 3, 2006
291
ES
Hi,

Imagine that I've got a SUBROUTINE with some local subroutines under a CONTAINS statement, like:
Code:
SUBROUTINE GlobalSub
IMPLICIT NONE
INTEGER :: i

i=1

CONTAINS

   SUBROUTINE LocalSub
   IMPLICIT NONE
   INTEGER :: i
   DO i=1,10,1
      WRITE(*,*)'the global variable i shouldn't change due to the local i here, should it? But it does'
   END DO
   END SUBROUTINE LocalSub

END SUBROUTINE GlobalSub

In that case, the global "i" exists in the local subroutine right?
If I accidently define "i" again, thinking that I'm dealing with a new local variable, my global variable i will change unintentionally.

Is there a way to make gfortran check for this by means of any compiler option?

Of course if I just use "i" locally, the compiler may never find out, but if I redeclare it like "INTEGER :: i", the compiler might be able to conclude that I'm mistaken (which is what happened here)

Thanks,

Gerrit
 
If you declare INTEGER::i in LocalSub, LocalSub cannot use the global variable "i" and therefore cannot change that global variable.

Demonstration :

Code:
Program test
IMPLICIT NONE
INTEGER :: i

i=1

CALL LocalSub

Write(*,*) 'global i ',i

CONTAINS

   SUBROUTINE LocalSub
   IMPLICIT NONE
   INTEGER :: i
   i=10
   WRITE(*,*) 'local i',i
   END SUBROUTINE LocalSub

END program

Result :

Code:
coul@b10p5001:~$ ifort t48.f90
coul@b10p5001:~$ ./a.out
 local i          10
 global i            1

As you see, the global variable did not change.

Let us precise that declaring "i" as global variable is really a bad idea. "i" is usually a loop index which is typically a local variable. Here, the risk is to forget to declare "i" in the local subroutine. A classical mistake rather difficult to find, the global variable being modified unintentionally by a subroutine which compiles without warning.

François Jacq
 
Thanks, I ran your program and indeed, "i" had a local value where it had to be local (in gfortran as well).

It's some time ago I had this error and maybe I simply forgot to declare it.

Though usually, the "IMPLICIT NONE" statement will warn you for this, in this case it won't.

It seems I'll never become a big fan of local procedures.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top