1

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

For example:

program test
  implicit none

  integer :: n
  integer :: time

  print*, "enter n" ! this will be a constant value for the whole program
  call Calcul(time)
  print*, time  
end program

subroutine Calcul(Time)
  implicit none

  integer :: time 

  ! i don't want to declare the constant n again and again because some times the subroutines have a lot of variables.  
  time = n*2 
end subroutine

Sometimes there are a lot of constants that are defined by the user and I will make a lot of subroutines that use those constants, so I want to stock them and and use them without redefining them again and again.

veryreverie
  • 2,871
  • 2
  • 13
  • 26
  • 2
    You have to use modules. Also, do not call `n` a constant. It is a variable. You are changing it in the `read` statement. – Vladimir F Героям слава Feb 27 '17 at 10:52
  • See http://stackoverflow.com/questions/42024559/using-global-variables-in-fortran and http://stackoverflow.com/questions/19040118/how-to-avoid-global-variables-in-fortran-90-or-higher http://stackoverflow.com/questions/1240510/how-do-you-use-fortran-90-module-data and others (possible duplicate. – Vladimir F Героям слава Feb 27 '17 at 10:55

1 Answers1

5

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.