Dadep
Dadep

Reputation: 2788

Common block and subroutine argument

If I have a variable called var which is in a common block named myCB may I use the same name to pass an argument between two other subroutines which are not using the common block myCB?

The code is like below.

Subroutine SR1(Var)
      !something here using Var
end Subroutine SR1

Subroutine SR2()
....
      Call SR1(B)
....
end Subroutine SR2

Subroutine SR3()
common \myCB\ Var
... 
  ! something using the other Var shared with SR4
......
end Subroutine SR3

Subroutine SR4()
common \myCB\ Var
....
... ! something using the other Var shared with SR3
....
end Subroutine SR4

I do have problem with Var passing between SR1 and SR2, could the problem come from the other named Var in the common block ?

Upvotes: 1

Views: 635

Answers (1)

jlokimlin
jlokimlin

Reputation: 593

If you don't want to modify the legacy code base too much, I suggest you put the common block in a module and import the variables when access is required:

module myCB_mod
    common /myCB/ var, var2, var3
    save ! This is not necessary in Fortran 2008+
end module myCB_mod

subroutine SR2()
    use myCB_mod
    !.......
    call SR1(B)
    !.....
end subroutine SR2

subroutine SR3()
    use myCB_mod
    !.......
end subroutine SR3

subroutine SR4()
    use myCB_mod
    !.....
end subroutine SR4

or better yet, I suggest you avoid common blocks altogether (this requires a full rewrite of the legacy code base) and confine all your subroutines inside a module

module myCB
    implicit none
    real var, var2, var3
    save ! This is not necessary in Fortran 2008+
end module myCB

module mySubs
    use myCB
    implicit none
contains
    subroutine SR2()
            !.......
            call SR1(B)
            !.....
    end subroutine SR2

    subroutine SR3()
            !.......
    end subroutine SR3

    subroutine SR4()
            !.....
    end subroutine SR4
end module

Lastly, do the variables in your common block require initialization? If so, this introduces even further complications involving data statements or even the block data construct.

Upvotes: 2

Related Questions