Common block and subroutine argument

六眼飞鱼酱① 提交于 2019-12-23 03:41:42

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/40936915/common-block-and-subroutine-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!