How to avoid declaring and setting the value of a variable in each subroutine?

后端 未结 1 1882
无人共我
无人共我 2021-01-29 05:43

How to avoid repeated declaration of a variable that has a constant value in subroutines?

For example:

program test

implicit none

integer :: n

integer         


        
相关标签:
1条回答
  • 2021-01-29 06:15

    For global variables use modules (old FORTRAN used common blocks, but they are obsolete):

    module globals
      implicit none
    
      integer :: n
    
    contains
    
      subroutine read_globals()    !you must call this subroutine at program start
    
        print*, "enter n" ! this will be a constant value for the whole program
        read *, n
      end subroutine
    end module
    
    !this subroutine should be better in a module too !!!
    subroutine Calcul(Time)
      use globals !n comes from here
      implicit none
    
      integer :: time 
      time = n*2
    end subroutine
    
    program test
      use globals ! n comes from here if needed
      implicit none
    
      integer :: time
    
      call read_globals()
    
      call Calcul(time)
    
      print*, time
    end program
    

    There are many questions and answers explaining how to use Fortran modules properly on Stack Overflow.

    0 讨论(0)
提交回复
热议问题