'How to avoid declaring and setting the value of a variable in each subroutine?
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | Vladimir F ГероÑм Ñлава | 
